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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!