本文介绍了通过数组值的键路径设置多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对不起,标题太糟糕了,我当时能想到的最好的!假设我有一个像这样的路径"数组;
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()
)
)
)
)
推荐答案
只需使用 array_shift 或 array_pop 之类的东西迭代它:
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,);
这篇关于通过数组值的键路径设置多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!