du512926 2015-11-01 12:09
浏览 411
已采纳

从JSON文件创建foreach循环

I have a json file (items.json) that looks like following:

{"response":{"success":1,"current_time":1446373851,"items":[
{
"Item1": {"last_updated":1446372015,"quantity":73,"value":1200},
"Item2": {"last_updated":1446372015,"quantity":40,"value":5297},
"Item3": {"last_updated":1446372015,"quantity":148,"value":2507}
}]}}

I've tried to create a for loop to create elements with values from each item in the json:

$values = file_get_contents( $siteurl.'/json/items.json');
$values = json_decode($values);

foreach ($values->items as $key => $value) {

if($value==Item1 && $value->value>1000){
<p><?php echo $value->value ; ?></p>
}
}

In the above example i'm testing the first value in "items" (Item1). I'd like to be able to have a foreach for all these three items.

But the browser outputs the following error "Warning: Invalid argument supplied for foreach() in".

How do I correctly create a foreach where I can get values from all "items" objects (ex "Item1" and "Item2) that works for my json file format.

  • 写回答

3条回答 默认 最新

  • douxing6532 2015-11-03 03:29
    关注

    Your items are actually within the "response" object, and then you have the items object wrapped in an array as well. If you are unabled to edit items.json then you can do

    $values = file_get_contents( $siteurl.'/json/items.json');
    $values = json_decode($values);
    
    foreach ($values->response->items as $key => $value) {
       foreach($value as $key => $value) {
           if($key == 'Item1' && $value->value > 1000) {
               echo $value->value;
            }
        }
    }
    

    A better solution however would be to remove the array from items.json (square brackets) as it seems to be redundant and then do:

    $values = file_get_contents( $siteurl.'/json/items.json');
    $values = json_decode($values);
    
    foreach ($values->response->items as $key => $value) {
        if($key == 'Item1' && $value->value > 1000) {
            echo $value->value;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗