简体   繁体   中英

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:

{"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()

As you have mark return as array true in json_decode . 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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