繁体   English   中英

PHP JSON和数组

[英]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']) ,但是foreach在$location['street']上循环。 因此,很可能您的foreach值已反转。

如果var_dump被信任,那么您甚至不需要foreach循环:

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

$location['street'] ..您在哪里分配的? 不是$street['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/>';

您无需迭代数组即可访问街道信息。


如果要对存储在$street['location']['street']的数组使用foreach

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

(请注意,您可以不必使用来连接.如果你只是想echo的东西,可以只使用, 。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM