从树构建阵列递归函数 [英] Recursive function for building array from tree

查看:120
本文介绍了从树构建阵列递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,看起来像这样:

I have an array that looks like this:

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

下面是我使用递归函数,它的作品除了在某些情况下(其中深度越大它似乎。

Here is the recursive function that I'm using, it works except in some cases (where the depth is greater it seems.

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和名称将显示所有的深度?

Any idea how I can have it so the term_id and name is shown for all depths?

推荐答案

试试这个:

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

这篇关于从树构建阵列递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆