Tobias
Tobias

Reputation: 95

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.

Upvotes: 0

Views: 2525

Answers (1)

d3v_1
d3v_1

Reputation: 579

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, e.g.

[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.

Upvotes: 1

Related Questions