Php 递归数组结构
可能重复:Php 递归数组结构,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'] = 'v
我有这样一个数组
$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);
除非我不知何故需要进入新阵列,并跟踪我在阵列中的深度。是否有人有这样做的示例脚本,或者有任何时髦的数组漫游技巧?该解决方案可以通过变量引用(也称为“指针”)实现,有关更多信息,请参阅
请去学习递归。@blockhead:注意,这个例子被称为“迭代”,因为它不使用递归。我不确定递归版本会是什么样子,但我邀请@blockhead或其他人尝试:-)
<?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));
?>