Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multi-dimensional array by key path from array values?

Tags:

arrays

php

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()
            )
        )
    )
)
like image 937
TheDeadMedic Avatar asked Jun 29 '10 21:06

TheDeadMedic


1 Answers

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,);
like image 80
Yann Vernier Avatar answered Sep 23 '22 22:09

Yann Vernier