从树中构建数组的递归函数

时间:2011-09-27 02:01:01

标签: php arrays recursion multidimensional-array tree

我有一个如下所示的数组:

Array (
    [0] => Array
    (
        [term_id] => 23
        [name] => testasdf
        [depth] => 1
    )
    [1] => Array
    (
        [term_id] => 26
        [name] => asdf
        [depth] => 2
    )
    [2] => Array
    (
        [term_id] => 31
        [name] => Another level deep
        [depth] => 3
    )
    [3] => Array
    (
        [term_id] => 32
        [name] => Another level deep
        [depth] => 2
    )
    [4] => Array
    (
        [term_id] => 24
        [name] => testasdf
        [depth] => 1
    )
    [5] => Array
    (
        [term_id] => 27
        [name] => asdf
        [depth] => 1
    )
)

这是我正在使用的递归函数,除了在某些情况下(它的深度看起来更大)它可以工作。

function process(&$arr, &$prev_sub = null, $cur_depth = 1) {
    $cur_sub = array();
    while($line = current($arr)){
        if($line['depth'] < $cur_depth){
            return $cur_sub; 
        }elseif($line['depth'] > $cur_depth){
            $prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 );
        }else{
            $cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']);
            $prev_sub =& $cur_sub[$line['term_id']];
            next($arr);
        }
    }
    return $cur_sub;
}

结果如下:

Array
(
    [23] => Array
    (
        [26] => Array
        (
            [31] => Array
            (
                [term_id] => 31
                [name] => Another level deep
            )
        )
        [32] => Array
        (
            [term_id] => 32
            [name] => Another level deep
        )
    )
    [24] => Array
    (
        [term_id] => 24
        [name] => testasdf
    )
    [27] => Array
    (
        [term_id] => 27
        [name] => asdf
    )
)

我知道如何才能拥有它,以便显示所有深度的term_id和名称?

1 个答案:

答案 0 :(得分:1)

试试这个:

function process(&$arr, &$prev_sub = null, $cur_depth = 1) {

  $cur_sub = array();
    while($line = current($arr)){
        if($line['depth'] < $cur_depth){
            return $cur_sub; 
        }
        if($line['depth'] > $cur_depth){
            $prev_sub = $this->process($arr, $cur_sub, $cur_depth + 1 );

        }

            $cur_sub[$line['term_id']] = array('term_id' => $line['term_id'], 'name' => $line['name']);
            $prev_sub =& $cur_sub[$line['term_id']];
            next($arr);
    }
  return $cur_sub;
}