【问题标题】:Recursive function for building array from tree从树构建数组的递归函数
【发布时间】:2011-11-25 16:19:07
【问题描述】:

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

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 和 name?

【问题讨论】:

    标签: php arrays recursion multidimensional-array tree


    【解决方案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;
    }
    

    【讨论】:

    • 这实际上匹配了正确的 ID,我认为在 term_id 以错误的顺序返回之前,但它仍然没有显示前两个节点的 term_id 和 name 值,似乎任何节点有孩子的,没有添加 term_id 和 name 数组
    猜你喜欢
    • 2020-02-27
    • 2012-12-14
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多