PHP JSON and array


PHP JSON and array

我查询了一个API,我在显示返回的代码(JSON)方面遇到了一些麻烦。如果我执行var_dump,就会得到如下内容:

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"
} 

现在,我通常会做这样的事情来显示它:

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/>';

但是我得到:

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

纬度/经度被截断,我无法获得街道id/名称…

谢谢你的帮助

这应该能解决街道问题:

$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/>';

您不需要迭代数组来访问街道信息。


如果您想将foreach用于存储在$street['location']['street']中的数组:

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

(注意,你可以不需要使用.连接时,你只是想echo的东西,可以只使用,)

您正在转储一个值($street['location'])),但在$location['street']上进行foreach循环。所以很可能你把foreach的值颠倒了。

如果var_dump是可信的,那么您甚至不需要foreach循环:

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