If I have the following array:
[
'foo',
'bar',
'baz'
]
How can I get this output with PHP dynamically:
[
'foo' => [
'bar' => [
'baz' => []
]
]
]
EDIT
I ended up achieving it by building the array backward and keeping track of the last key, but I would be interested in a cleaner recursive approach:
$arr = ['foo', 'bar', 'baz'];
$new_arr = [];
$last_key = null;
foreach ( array_reverse( $arr ) as $item ) {
if ( $last_key ) {
$new_arr[ $item ] = $new_arr;
unset( $new_arr[ $last_key ] );
$last_key = $item;
} else {
$new_arr[ $item ] = [];
$last_key = $item;
}
}
If you want to use a foreach
you don't have to unset or use an if/else.
You could reverse the $arr
, and wrap the $new_arr
(the result) inside a new array for each iteration using the value of $arr
as the key.
$arr = [
'foo',
'bar',
'baz'
];
$new_arr = [];
foreach(array_reverse($arr) as $v) {
$new_arr = [$v => $new_arr];
}
print_r($new_arr);
See a PHP demo.
Output
Array
(
[foo] => Array
(
[bar] => Array
(
[baz] => Array
(
)
)
)
)