2012-06-14 147 views
2

可能重复:
String with array structure to Array递归阵列结构

我有一个数组这样

$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

请去了解递归。 – blockhead

+1

@blockhead:http://stackoverflow.com/a/23882 –

回答

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

?> 
+0

请注意,此示例被称为“迭代”,因为它不使用递归。我不确定递归版本会是什么样子,但我邀请@blockhead或其他人尝试:-) – jchook

+0

非常感谢:) –