簡體   English   中英

json_decode到一個數組?

[英]json_decode to an array?

foreach ($likes as $like) {
    // Extract the pieces of info we need from the requests above
    $id = idx($like, 'id');
    $item = idx($like, 'name');

    fwrite($fileout,json_encode($like));
    fwrite($fileout,PHP_EOL );
}

$json_string = file_get_contents('testson.json');
$get_json_values=json_decode($json_string,true);

foreach ($get_json_values as $getlikes) {  ?>
          <li>
            <a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
          </li>
        <?php
      } 

打開瀏覽器時,會出現一個Warning: Invalid argument supplied for foreach() 我不明白為什么我的論點無效。

如果我添加if,沒有任何反應,這表明實際問題是什么。 但問題是什么是正確的方法 我很確定這很簡單,但我一直在努力奮斗一個多小時。 我的json文件有這樣的字段,所以我認為不存在問題:

{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762"}

請幫幫我,我真的厭倦了,我不知道該怎么辦。 那么...... 如何將文件解碼為數組呢?

您需要testson.json文件的內容而不僅僅是名稱!

通過PHP接收內容:

$json_string = file_get_contents('testson.json');

通過測試確保文件中有有效的JSON內容

var_dump(json_decode($json_string));

然后打電話

foreach (json_decode($json_string) as $getlikes) {  ?>

更新:當您保存文件並在幾毫秒后訪問它時,可能是文件系統太慢並且沒有向您顯示正確的內容。

fclose($fileout);
clearstatcache();

file_get_contents();之前file_get_contents(); 呼叫!

我建議使用file_put_contents()file_read_contents()來擺脫這些問題!

json_decode期待一個字符串作為它的第一個參數。 你正在傳遞我猜的文件名。 您應該首先加載文件...

$json = file_get_contents('testson.json');
$data = json_decode($json);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM