我有一个名为geometry的json对象,geometry密钥存储了称为path的数组,而该路径存储了多维数组
我试图遍历路径,但是循环仅返回第一个索引值
$result = curl_exec($ch);
foreach($JsonData->features as $chunk )
{
$geo =$chunk->geometry->paths;
echo $geo;
}
预期结果-将路径值存储到一个变量中。 实际结果-仅返回一个值。
数据是...
"geometry": { "paths": [ [ [ -9131174.97888261, 3120622.68129019 ],
[ -9131167.41739487, 3120625.21649344 ],
[ -9131007.49336538, 3120782.33590721 ],
[ -9130998.82313552, 3120791.07506482 ] ] ] }
答案 0 :(得分:0)
以下代码应使您重回正轨:
<?php
$json = '{ "paths": [ [ [ -9131174.97888261, 3120622.68129019 ], [ -9131167.41739487, 3120625.21649344 ], [ -9131007.49336538, 3120782.33590721 ], [ -9130998.82313552, 3120791.07506482 ] ] ] }';
$object = json_decode($json);
foreach($object->paths[0] as $path) {
$geo = $path;
echo $geo[0];
echo $geo[1];
}
答案 1 :(得分:0)
当您继续覆盖$geo
中的值时,您只会得到1个值。您应该构建一个数组(使用[]
添加每个值),这将为您提供所有结果。您可能还需要调整访问数据的方式,我已将循环更新为$JsonData->features->geometry->paths[0]
...
$geo = [];
foreach($JsonData->features->geometry->paths[0] as $chunk )
{
$geo[] =$chunk;
}
print_r($geo);
结果类似于...
Array
(
[0] => Array
(
[0] => -9131174.9788826
[1] => 3120622.6812902
)
[1] => Array
(
[0] => -9131167.4173949
[1] => 3120625.2164934
)
[2] => Array
(
[0] => -9131007.4933654
[1] => 3120782.3359072
)
[3] => Array
(
[0] => -9130998.8231355
[1] => 3120791.0750648
)
)