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;
}
}
CodePudding user response:
$arr = [ 'foo', 'bar', 'baz' ];
$new_arr = array_reduce(array_reverse($arr), static fn($carry, $item) => [ $item => $carry ], []);
Steps:
- Reverse the array.
- Reduce the reversed array. On each iteration return [ $item => $carry ].
CodePudding user response:
Try this:
function buildNestedArray($arr) {
if (!$arr) {
return [];
}
return [ $arr[0] => buildNestedArray(array_slice($arr, 1))];
}