简体   繁体   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
      } 

When opening the browser, there is a Warning: Invalid argument supplied for foreach() . 打开浏览器时,会出现一个Warning: Invalid argument supplied for foreach() I don't understand why would my arguments be invalid. 我不明白为什么我的论点无效。

If I add the if, nothing happens, which shows what the actual problem is. 如果我添加if,没有任何反应,这表明实际问题是什么。 But the question is WHAT IS THE PROPER WAY TO DO THIS ? 但问题是什么是正确的方法 I'm pretty sure it's very simple, but i've been struggling with this for more than an hour. 我很确定这很简单,但我一直在努力奋斗一个多小时。 My json files has fields like this, so I don't think there would be the problem: 我的json文件有这样的字段,所以我认为不存在问题:

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

Please help me, I really got tired with it, and I don't know what to do. 请帮帮我,我真的厌倦了,我不知道该怎么办。 So... how can I decode the file into an array? 那么...... 如何将文件解码为数组呢?

You need the contents of the testson.json file not just the name! 您需要testson.json文件的内容而不仅仅是名称!

Receive the contents via PHP: 通过PHP接收内容:

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

Make sure there are valid JSON contents in the file by testing it via 通过测试确保文件中有有效的JSON内容

var_dump(json_decode($json_string));

And then call 然后打电话

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

Update: When you save the file and access it miliseconds later it might be that the filesystem is too slow and not showing you the correct content. 更新:当您保存文件并在几毫秒后访问它时,可能是文件系统太慢并且没有向您显示正确的内容。

Add

fclose($fileout);
clearstatcache();

before the file_get_contents(); file_get_contents();之前file_get_contents(); call! 呼叫!

I recommend to use file_put_contents() and file_read_contents() to get rid of such problems! 我建议使用file_put_contents()file_read_contents()来摆脱这些问题!

json_decode is expecting a string as it's first parameter. json_decode期待一个字符串作为它的第一个参数。 You are passing what I'm guessing is a filename. 你正在传递我猜的文件名。 You should load the file first like so... 您应该首先加载文件...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM