设置多维通过关键路径从数组值数组? [英] Set multi-dimensional array by key path from array values?

查看:101
本文介绍了设置多维通过关键路径从数组值数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉的可怕称号,尽我可能当时想​​到的!说我有像这样一个路径阵列;

阵列('本','是','中','通路')

什么是下面?阵列

要结束了最有效的方法

 阵列(
    '这'=>阵列(
        '是'=>阵列(
            '的'=>阵列(
                '路径'= GT;阵列()
            )
        )
    )


解决方案

只需迭代它的东西,如array_shift或array_pop:

  $ inarray =阵列('本','是','中','通路');
$树=阵列();
而(计数($ inarray)){
    $树=阵列(array_pop($ inarray)=> $树);
}

没测试过,但是这是它的基本结构。递归也符合了任务。
另外,如果你不想修改初始数组:

  $ inarray =阵列('本','是','中','通路');
$结果=阵列();
的foreach(array_reverse($ inarray)为$键)
    $结果=阵列($关键=> $结果);

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

这篇关于设置多维通过关键路径从数组值数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆