将平面数组转换为树

时间:2014-09-19 09:24:03

标签: php arrays tree

我有以下数组:

array (size=543)
  0 => 
    array (size=3)
      0 => string '3' (length=1)
      1 => string '1' (length=1)
      2 => string 'a' (length=1)
  1 => 
    array (size=3)
      0 => string '5' (length=1)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)
  2 => 
    array (size=3)
      0 => string '6' (length=1)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)
  3 => 
    array (size=3)
      0 => string '8' (length=1)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)
  4 => 
    array (size=3)
      0 => string '9' (length=1)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)
  5 => 
    array (size=3)
      0 => string '10' (length=2)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)
  6 => 
    array (size=3)
      0 => string '11' (length=2)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)
  7 => 
    array (size=3)
      0 => string '12' (length=2)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)
  8 => 
    array (size=3)
      0 => string '14' (length=2)
      1 => string '3' (length=1)
      2 => string 'a' (length=1)

如何将此数组转换为"树数组",以便我可以生成HTML ul列表?我一直在考虑使用以下功能:

function generatePageTree($datas, $parent = 0, $depth = 0){
    if($depth > 1000) return ''; // Make sure not to have an endless recursion
    $tree = '';
    for($i=1, $ni=count($datas); $i < $ni - 1; $i++){
        if($datas[$i][1] == $parent){
            $tree .= str_repeat('-', $depth);
            $tree .= 'fsdfdsdf' . '<br/>';
            $tree .= $this->generatePageTree($datas, $datas[$i][0], $depth+1);
        }
    }
    return $tree;
}

但是它会产生空数组......错误的是什么,我怎么能这样做?谢谢!

所以我应该得到类似的东西:

array(size=543)
  0 =>
    array(size=2)
      0 => string '1'
      1 => array(size=2)
        0 => string '2'

0 个答案:

没有答案