2014-02-08 77 views
0

我在PHP这样的一个数组:阵列到阵列的树PHP

Array 
(
    [0] => Array 
     (
      [ref] => a 
      [ref_father] => 0 
     ) 

    [1] => Array 
     (
      [ref] => b 
      [ref_father] => 0 
     ) 
    [2] => Array 
     (
      [ref] => c 
      [ref_father] => a 
     ) 

如何从这个数组创建树是这样的:

Array 
(
    [0] => Array 
     (
      [ref] => a 
      [ref_father] => 0 
     ) 

    [1] => Array 
     (
      [ref] => c 
      [ref_father] => a 
     ) 
    [2] => Array 
     (
      [ref] => b 
      [ref_father] => 0 
     ) 

意味着我要展示父亲和每个父亲的下面他的儿子。谢谢

+2

使用二维数组数据结构来表示树结构将无法正常工作。在有限的情况下,它可以工作,比如表示一个堆,但是一般情况下你会想用树数据结构来表示一棵树。 –

+0

@MikyDinescu:如果我有一维数组数据结构?? – 2dar

+0

一维数组不足以表示树。 –

回答

0

我会遍历基础数组,并创建一个新的数组与父亲作为索引和他们的所有孩子在一个数组中。

新的阵列看起来是这样的:

Array 
(
    [0] => Array('a', 'b') // 0 Is the base root 
    ['a'] => Array('c') 

    ['b'] => Array() 
    ['c'] => Array() 

然后,你可以使用这样的功能:

$a = array(
    0 => array('a', 'b'), 
    'a' => array('c'), 
    'b' => array(), 
    'c' => array() 
); 

$depth_array = array(); 

function build_depth($key, $mapped_array) { 
    if (array_key_exists($key, $mapped_array)) { 
     if (count($mapped_array[$key]) == 0) return array(); 
     else { 
      foreach($mapped_array[$key] as $child) { 
       return array($child => build_depth($child, $mapped_array)); 
      } 
     } 
    } 
} 

foreach ($a[0] as $root_child) { 
    $depth_array[$root_child] = build_depth($root_child, $a); 
} 

这将递归构建深度无论深度。 测试在这里: http://phptester.net/