doudui1850 2019-01-16 00:11
浏览 37
已采纳

嵌套Json php for循环状态[0]问题

Hi I have a Json format like below:

{
   "result":0,
   "status":[
      {
         "id":"00001",
         "vid":"yes"
      },
      {
         "id":"00002",
         "vid":"yes"
      },
      {
         "id":"00003",
         "vid":"no"
      }
   ]
}

I want to use the json_decode function in PHP to decode the id values such as below:

 00001
 00002
 00003

here is the code I am using:

$url = file_get_contents("URL");

foreach(json_decode($url, true) as $key=>$value){
    foreach($value->status[0] as $key1=>$value1){
        echo $value1->id;
    }
}

The problem seems to be with status[0] as far as I know using status[0] is the only way to select the status key. However I can't get the loop to work correctly.

I get the error: Trying to get property of non-object meaning status[0] is not finding status in the Json array however I have no idea why this is since it works when I pull a value like:
$id = $url->status[0]->id;

If anyone has any suggestions or advice I'd greatly appreciate it. Thanks

  • 写回答

3条回答 默认 最新

  • doupao5296 2019-01-16 00:24
    关注

    I removed some commas from your json data.

    Code: demo: https://3v4l.org/C1Mda

    $json = '{"result":0,"status":[{"id":"00001"},{"id":"00002"},{"id":"00003"}]}';
    
    foreach(json_decode($json, true)['status'] as $status){
        echo $status['id'] , "
    ";
    }
    

    Output:

    00001
    00002
    00003
    

    Because you are using json_decode's true parameter, an array is generated. You need to use square bracket syntax.

    Or you can use objects:

    foreach(json_decode($json)->status as $status){
        echo $status->id , "
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动