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

前端 未结 5 1596
南笙
南笙 2020-12-10 18:38

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\')

5条回答
  •  爱一瞬间的悲伤
    2020-12-10 19:10

    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,);
    

提交回复
热议问题