代码之家  ›  专栏  ›  技术社区  ›  Jacob Raccuia

从递归函数创建平面数组,而不是在

  •  0
  • Jacob Raccuia  · 技术社区  · 11 年前

    我有一个递归函数,它做了很多功能和一些数据库调用,以及不创建一些很酷的东西。我想把每次调用函数的结果保存到一个数组中。

    所以我这样做了,得到了一个多维数组,其结构与函数的结果类似。它看起来是这样的:

    Array
    (
        [0] => 2507
        [1] => Array
            (
                [0] => 2508
            )
    
        [2] => 2073
        [3] => Array
            (
                [0] => 2397
            )
    )
    

    我可以使用PHP 5.3轻松地将其压平 array_walk_recursive .

    然而,我更希望我不需要在原始函数之后调用另一个函数,因为这似乎是多余的。

    如何从每次调用都“创建”数据的递归函数中创建平面数组?

    我试着截断了我的递归函数。。。

    function get_children() {
        $leaf = new array();
    
        $results = database_call();
        foreach($results as $res) {
            $leaf[] = $res;
    
            // do tons of stuff not included
            if($res->children == 1) {   
               $leaf[] = get_children();
            }
        }
    return $leaf;
    }
    
    $i_wish_this_was_flat = get_children();
    
    1 回复  |  直到 11 年前
        1
  •  2
  •   Howard    11 年前

    也许你可以用

    $leaf = array_merge($leaf, get_children());
    

    而不是

    $leaf[] = get_children();