如何通过定义特定键来访问php中嵌套数组中的所有值?
I am creating an routing application and get the result as an json array. After transforming it into an php array i get the whole distance and whole duration correctly. Now i need for every value in the key "legs" the distances and durations too but all i did to get the data doesnt work.
The json output of the array looks like this:
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',
)
The whole distance (43214.8) and whole duration (5689.7) i get by the following code:
foreach($res2['routes'] as $item)
{
$distances = array_push_assoc($distances, $item['distance'], $item['duration']);
}
In order to get the distances and durations i did the following:
foreach($res2['routes']['legs'] as $item)
{
$durations = array_push_assoc($durations , "DUR", $item['duration']);
}
How can i get the distances and durations from "legs"? Why doenst work $res2['routes']['legs']?
Thank you!
Do notice the the "legs" array exists in index 0 of the "routes" array so looping on it will require using $res2['routes'][0]['legs']
.
Morever, notice that using array_push_assoc
in loop with the same hard-coded key (as "DUR" in your example) will override the key each time so your data gets lost - you better change it to:
foreach($res2['routes'][0]['legs'] as $item) {
$durations[] = $item['duration'];
}