Sorry for the terrible title, best I could think of at the time! Say I have a 'path' array like so;
array('this', 'is', 'the', 'path')
What would be the most effective method to end up with the array below?
array(
'this' => array(
'is' => array(
'the' => array(
'path' => array()
)
)
)
)
Just iterate over it with something like array_shift or array_pop:
$inarray = array('this', 'is', 'the', 'path',);
$tree = array();
while (count($inarray)) {
$tree = array(array_pop($inarray) => $tree,);
}
Not tested, but that's the basic structure of it. Recursion also fits the task well. Alternatively, if you don't want to modify the initial array:
$inarray = array('this', 'is', 'the', 'path',);
$result = array();
foreach (array_reverse($inarray) as $key)
$result = array($key => $result,);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With