2

可能重复:
具有数组结构的字符串到数组

我有一个这样的数组

$foo = array();
$foo['/'] = 'value';
$foo['/foo'] = 'value';
$foo['/foo/bar'] = 'value';
$foo['/test'] = 'value';
$foo['/test/tester'] = 'value';
$foo['/hello'] = 'value';
$foo['/hello/world'] = 'value';
$foo['/hello/world/blah'] = 'value';

我需要做的是将这些子页面存储在树状结构中,因此需要自动将其转换为:

   $foo = array(
    '/' => array(
        'value' => 'value',
        'children' => array(
            '/foo' => array(
                'value' => 'value',
                'children' => array(
                    '/foo/bar' => array(
                        'value' => 'value',
                        'children' => array()
    );

我想我会做的事情是这样的:

$newArray = array();
foreach( $foo as $key => $val )
{
    $bits = explode('/', $key);

    foreach( $bits as $bit )
    {
        $newArray[$bit] = array('val' => $val);
    }
}

print_r($newArray);

除了我以某种方式需要进入 newArray,并跟踪我在数组中的深度。有没有人有他们如何做到这一点的示例脚本,或者有任何时髦的阵列步行技巧?

4

1 回答 1

3

该解决方案可以通过变量引用(又名“指针”)来实现,更多信息请参见http://php.net/manual/en/language.references.php

<?php

$foo = array();
$foo['/'] = 'value';
$foo['/foo'] = 'value';
$foo['/foo/bar'] = 'value';
$foo['/test'] = 'value';
$foo['/test/tester'] = 'value';
$foo['/hello'] = 'value';
$foo['/hello/world'] = 'value';
$foo['/hello/world/blah'] = 'value';

function nest(&$foo)
{
    $new = array();
    foreach ($foo as $path => $value)
    {
        $pointer =& $new;
        $currentPath = '';
        if ($pathParts = explode('/', trim($path, '/'))) {
            while($nextKey = array_shift($pathParts)) {
                $currentPath .= '/' . $nextKey;
                if (!isset($pointer['children'][$currentPath])) {
                    $pointer['children'][$currentPath] = array();
                }
                $pointer =& $pointer['children'][$currentPath];
            }
        }
        $pointer['value'] = $value;
    }
    return $new ? array('/' => $new) : array();
}

print_r($foo);
print_r(nest($foo));

?>
于 2012-06-14T17:38:36.703 回答