Add elements to sub-array recursively
I'm trying to add elements to a sub array of the sub array where they were added in the previous iteration, i.e. transforming this:
$a = array('a', 'b', 'c');开发者_开发技巧
Into this:
$new_array = array(
'a' => array(
'b' => array(
'c' => array()
)
)
);
$a = array('a', 'b', 'c');
$tmp = array_reverse($a);
$new_array = array();
foreach ($tmp as $item) { $new_array = array($item => $new_array); }
function makeArrayChain($chain)
{
$key = array_shift($chain);
if ($key === NULL) {
return array();
} else {
return array($key => makeArrayChain($chain));
}
}
var_dump(makeArrayChain(array('a', 'b', 'c'));
array(1) {
["a"]=>
array(1) {
["b"]=>
array(1) {
["c"]=>
array(0) {
}
}
}
}
Similar to @aibs solution.
<?php
function splitIntoSubArray($array) {
return $array ? array(array_shift($array) => splitIntoSubArray($array)) : array();
}
$a = array('a', 'b', 'c');
print_r(splitIntoSubArray($a));
Output:
Array
(
[a] => Array
(
[b] => Array
(
[c] => Array
(
)
)
)
)
精彩评论