Olivier
Olivier

Reputation: 130

PHP JSON and array

I've querying an API and I've got some troubles to display the code returned (JSON). If I do a var_dump, I have something like this:

var_dump($street['location']);

array(3) {
    ["latitude"]=> string(10) "52.6397278"
    ["street"]=> array(2) {
        ["id"]=> int(469)
        ["name"]=> string(23) "On or near Abbey Street"
    }
    ["longitude"]=> string(10) "-1.1322920"
} 

Now, usually, I will do something like that to have it displayed:

var_dump($street['location']);
echo '->latitude:' . $location['latitude'] . '<br/>';
foreach($location['street'] as $st){
    echo '-->street id:' . $st['id'] . '<br/>';
    echo '-->street name:' . $st['name'] . '<br/>';
}
echo '->Longitude:' . $location['longitude'] . '<br/>';

But I get:

array(3) {
    ["latitude"]=> string(10) "52.6397278"
    ["street"]=> array(2) {
        ["id"]=> int(469)
        ["name"]=> string(23) "On or near Abbey Street"
    }
    ["longitude"]=> string(10) "-1.1322920"
} ->latitude:5

Warning: Invalid argument supplied for foreach() in /home/pasd529/public_html/npia.php on line 102
->Longitude:5

The latitude / longitude are truncated and I can't get the streed id / name ...

Thanks for your help

Upvotes: 0

Views: 136

Answers (2)

middus
middus

Reputation: 9121

This should solve the problem with the street:

$street['location'] = // array - it's not really clear in your code.   
echo '->latitude:' . $street['location']['latitude'] . '<br/>';
echo '-->street id:' . $street['location']['street']['id'] . '<br/>';
echo '-->street name:' . $street['location']['street']['name'] . '<br/>';
echo '->Longitude:' . $street['location']['longitude'] . '<br/>';

You do not need to iterate ofer the array to access the street information.


If you want to use foreach for the array stored in $street['location']['street']:

// ...
foreach($street['location']['street'] as $key => $value){
   echo '-->street ', $key, ': ', $value, '<br />';
}
// ...

(Note that you can don't need to concatenate using . when you just want to echo something and can just use the ,.)

Upvotes: 1

Marc B
Marc B

Reputation: 360922

You're dumping out one value ($street['location']), but are foreach looping on $location['street'] instead. So most likely you've got your foreach value reversed.

If the var_dump is to be trusted, then you don't even need the foreach loop:

echo '->latitude:' . $location['latitude'] . '<br/>';
echo '-->street id:' . $location['street']['id'] . '<br/>';
echo '-->street name:' . $location['street']['name'] . '<br/>';

Upvotes: 0

Related Questions