0

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.

3
  • 4
    there is not enough information in this question for us to be able to help you. Please post a sample of the JSON. Commented Jan 11, 2017 at 21:31
  • 2
    It's hard to tell what the problem is without some associated JSON. Also some more information on $myInstance, specifically its method getData, would help. Commented Jan 11, 2017 at 21:37
  • Since it works correclty when I declare $i =1 the correct entry is shown of array[1]['name']. The json entries doesn't matter at this point. The problem is focused on $value[$i] - why does it not iterate ? It should or am i wrong ? Commented Jan 11, 2017 at 21:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thats it awesome d3v_1 ! I just dont know why a nested loop is necessary at this point. i accept your answer asap. THX a lot :)
The data in $json might be a 3D array with the key of zero. I'll edit my answer to explain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.