通过数组值的关键路径设置多维数组?

The*_*dic 4 php arrays

抱歉可怕的头衔,当时我能想到的最好!假设我有一个像这样的"路径"数组;

array('this', 'is', 'the', 'path')

什么是最有效的方法来结束下面的数组?

array(
    'this' => array(
        'is' => array(
            'the' => array(
                'path' => array()
            )
        )
    )
)
Run Code Online (Sandbox Code Playgroud)

Yan*_*ier 6

只需使用array_shift或array_pop等迭代它:

$inarray = array('this', 'is', 'the', 'path',);
$tree = array();
while (count($inarray)) {
    $tree = array(array_pop($inarray) => $tree,);
}
Run Code Online (Sandbox Code Playgroud)

没有经过测试,但这是它的基本结构.递归也很适合这项任务.或者,如果您不想修改初始数组:

$inarray = array('this', 'is', 'the', 'path',);
$result = array();
foreach (array_reverse($inarray) as $key)
    $result = array($key => $result,);
Run Code Online (Sandbox Code Playgroud)


Ven*_* D. 6

我使用两个类似的函数来获取和设置数组中的路径值:

function array_get($arr, $path)
{
    if (!$path)
        return null;

    $segments = is_array($path) ? $path : explode('/', $path);
    $cur =& $arr;
    foreach ($segments as $segment) {
        if (!isset($cur[$segment]))
            return null;

        $cur = $cur[$segment];
    }

    return $cur;
}

function array_set(&$arr, $path, $value)
{
    if (!$path)
        return null;

    $segments = is_array($path) ? $path : explode('/', $path);
    $cur =& $arr;
    foreach ($segments as $segment) {
        if (!isset($cur[$segment]))
            $cur[$segment] = array();
        $cur =& $cur[$segment];
    }
    $cur = $value;
}
Run Code Online (Sandbox Code Playgroud)

然后你像这样使用它们:

$value = array_get($arr, 'this/is/the/path');
$value = array_get($arr, array('this', 'is', 'the', 'path'));
array_set($arr, 'here/is/another/path', 23);
Run Code Online (Sandbox Code Playgroud)