我正在创建路由应用程序,并将结果作为json数组获取。将其转换为php数组后,我正确地获得了整个距离和整个持续时间。现在,我也需要键“腿”中的每个值的距离和持续时间,但我所做的所有操作都无法获得数据。
数组的json输出如下:
array (
'routes' =>
array (
0 =>
array (
'legs' =>
array (
0 =>
array (
'summary' => '',
'weight' => 3741.9,
'duration' => 2912.3, // This value is what i want access
'steps' =>
array (
),
'distance' => 21603.1, // This value is what i want access
),
1 =>
array (
'summary' => '',
'weight' => 3642.1,
'duration' => 2777.4, // This value is what i want access
'steps' =>
array (
),
'distance' => 21611.8, // This value is what i want access
),
),
'weight_name' => 'routability',
'weight' => 7384,
'duration' => 5689.700000000001, // This value i can acesss
'distance' => 43214.899999999994, // This value i can acesss too
),
),
'waypoints' =>
array (
0 =>
array (
'hint' => '',
'distance' => 16.78277948979663, // This value is what i want access
'name' => 'Weg',
'location' =>
array (
0 => 11.4623,
1 => 50.7126,
),
),
1 =>
array (
'hint' => '',
'distance' => 16.62835508134535,
'name' => 'Weg',
'location' =>
array (
0 => 12.6069,
1 => 51.5398,
),
),
2 =>
array (
'hint' => '',
'distance' => 16.78277948979663,
'name' => 'Weg',
'location' =>
array (
0 => 12.343,
1 => 51.576,
),
),
),
'code' => 'Ok',
)
我通过以下代码获得了总距离(43214.8)和整个持续时间(5689.7):
foreach($res2['routes'] as $item)
{
$distances = array_push_assoc($distances, $item['distance'], $item['duration']);
}
为了获得距离和持续时间,我做了以下事情:
foreach($res2['routes']['legs'] as $item)
{
$durations = array_push_assoc($durations , "DUR", $item['duration']);
}
我如何从“腿”获得距离和持续时间?为什么要执行$ res2 ['routes'] ['legs']?
谢谢!
答案 0 :(得分:0)
请注意,“腿”数组存在于“路线”数组的索引0中,因此要在其上循环将需要使用$res2['routes'][0]['legs']
。
此外,请注意,array_push_assoc
与相同的硬编码密钥(如示例中的“ DUR”)一起循环使用会每次均覆盖该密钥,因此您的数据会丢失-您最好将其更改为: / p>
foreach($res2['routes'][0]['legs'] as $item) {
$durations[] = $item['duration'];
}