<?php
$levels = ['country','state','city','location'];
$locations = [
['country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'street'=>'7th Ave', 'count'=>123],
['country'=>'USA', 'state'=>'Maryland', 'city'=>'Baltimore', 'location'=>'Harber', 'count'=>24],
['country'=>'USA', 'state'=>'Michigan', 'city'=>'Lansing', 'location'=>'Midtown', 'building'=>'H2B', 'count'=>7],
['country'=>'France', 'state'=>'Sud', 'city'=>'Marseille', 'location'=>'Centre Ville', 'count'=>12],
];
$output = [];
foreach($locations as $loc){
$str_to_eval='$output';
for($i=0;$i<count($levels);$i++){
$str_to_eval .= "[\$loc[\$levels[$i]]]";
}
$str_to_eval .= "=\$loc['count'];";
eval($str_to_eval);
}
print_r($output);
- Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- Array
(
[USA] => Array
(
[New York] => Array
(
[NYC] => Array
(
[Central Park] => 123
)
)
[Maryland] => Array
(
[Baltimore] => Array
(
[Harber] => 24
)
)
[Michigan] => Array
(
[Lansing] => Array
(
[Midtown] => 7
)
)
)
[France] => Array
(
[Sud] => Array
(
[Marseille] => Array
(
[Centre Ville] => 12
)
)
)
)
preferences:
107.34 ms | 411 KiB | 5 Q