简体   繁体   中英

PHP echo json with key value

why does this code not work correctly or what am I doing incorrectly?

$json = json_encode($myInstance->getData($id));
    $result = json_decode($json,true);
    $i = 0;
    foreach ($result as $value) {
        echo '<div>'.$value[$i]['name'].'</div>';
        $i++;
    }

The first value is shown correctly but it doesn't iterate through! Is $value[$i]['name'] not build for iterating?? It Only prints the array[0] not the array[1] . Thanks.

You'd be better off using nested foreach loops, not generally great coding practice but it'll do the job you're trying to do.

$json = json_encode($myInstance->getData($id));
$result = json_decode($json,true);

foreach ($result as $value) {
    foreach($value as $value_detail) {
        echo '<div>'.$value_detail['name'].'</div>';
    }
}

Your code will loop through all of the first level items in your JSON and display the first name from the first item, the second name from the second item, third from the third item, etc.

The issue you are having might be because the $json array is 3D, eg

[0 => 
  [ 
    ['name' => 'Foo'], ['name' => 'Bar'] 
  ] 
]

If that's the case then you might find that the foreach loop can be

foreach($result[0] as $value) {
    echo '<div>'.$value['name'].'</div>';
}

Try var_dump($result); to see what the data looks like.

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