简体   繁体   English

如何在PHP中浏览JSON数组中的每个元素

[英]How to go through each element in JSON array in PHP

I want to echo out each element of an object of a JSON array like this: 我想要回显出JSON数组的对象的每个元素,如下所示:

{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]}

But i cannot do it.I tried somethinglikethis: 但我不能这样做。我尝试过这样的事情:

$object = json_decode($json, true);
$request_list = $object->request_list;
foreach($request_list as $r){
    echo $r->name;
    echo $r->blood_type;
    echo $r->phone_number;
}

But I got an error like: 但我得到一个错误:

Invalid argument supplied for foreach() 为foreach()提供的参数无效

As you have mark return as array true in json_decode . 因为你在json_decode标记返回为数组true。 So, try below code. 所以,试试下面的代码。

 $object = json_decode($json, true);
 $request_list = $object['request_list'];
 foreach($request_list as $r){
    echo $r['name'];
    echo $r['blood_type'];
    echo $r['phone_number'];
}

Use this 用这个

$object = json_decode($json, true);
$request_list = $object['request_list'];
foreach($request_list as $r){
    echo $r['name'];
    echo $r['blood_type'];
    echo $r['phone_number'];
}

try 尝试

    $json = '{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]}';
    $data = json_decode($json );

    $request = $data->request_list;

    foreach($request as $request_data){
        echo $request_data->id;
        echo $request_data->name;
        echo $request_data->surname;
    }

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

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