Reputation: 43
This one has me stumped. I've searched and found similar questions but I can't seem to find any questions that match my exact problem.
In PHP, I have an array like so:
<?php
$array = array('one', 'two', 'three', 'four');
?>
I want to convert this into a multi-dimensional array like the following:
<?php
$new_array = array('one' => array('two' => array('three' => array('four' => NULL))));
// or, to put another way:
$new_array['one']['two']['three']['four'] = NULL;
?>
Bearing in mind I do not know how many items will be in the original array, I need a way to recursively create a multi-dimensional associated array.
It seemed like an easy thing to do, but I can't seem to figure this out.
Upvotes: 4
Views: 2901
Reputation: 88677
function recursive_array_convert ($input, &$result = array()) {
$thisLevel = array_shift($input);
if (count($input)) {
if (!isset($result[$thisLevel]) || !is_array($result[$thisLevel])) {
$result[$thisLevel] = array();
}
recursive_array_convert($input, $result[$thisLevel]);
} else {
$result[$thisLevel] = NULL;
}
return $result;
}
This function should give you a lot of flexibility - you can simply pass the input array to the first argument and catch the result in the return, or you can pass an existing variable to the second argument to have it filled with the result. This means that you can achieve what you want in you example with:
$result = recursive_array_convert(array('one', 'two', 'three', 'four'));
...or...
recursive_array_convert(array('one', 'two', 'three', 'four'), $result);
At first glance there may seem little point in this option, but consider the following:
$result = array();
recursive_array_convert(array('one', 'two', 'three', 'four'), $result);
recursive_array_convert(array('five', 'six', 'seven', 'eight'), $result);
print_r($result);
/* Output:
Array
(
[one] => Array
(
[two] => Array
(
[three] => Array
(
[four] =>
)
)
)
[five] => Array
(
[six] => Array
(
[seven] => Array
(
[eight] =>
)
)
)
)
*/
As you can see, the function can be used to create as many chains as you like in the same variable.
Upvotes: 1
Reputation: 67715
You can do that easily with references:
$out = array();
$cur = &$out;
foreach ($array as $value) {
$cur[$value] = array();
$cur = &$cur[$value];
}
$cur = null;
Printing $out
should give you:
Array
(
[one] => Array
(
[two] => Array
(
[three] => Array
(
[four] =>
)
)
)
)
Upvotes: 5