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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度