我有一个数组
$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,并跟踪我对阵列的深度。有没有人有一个示例脚本,他们是如何做到这一点,或有任何时髦的阵列步骤提示这样做?
答案 0 :(得分: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));
?>