递归函数从数组中自下而上计算总数

时间:2011-07-07 15:04:03

标签: php arrays recursion

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

Array
(
    [0] => Array
        (
            [id] => 5
            [title] => Books
            [total_links] => 3
            [subcategories] => Array
                (
                    [0] => Array
                        (
                            [id] => 6
                            [title] => Jeffrey Archer
                            [total_links] => 1
                            [subcategories] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 8
                                            [title] => Political
                                            [total_links] => 2
                                            [subcategories] => Array
                                                (
                                                )

                                        )

                                    [1] => Array
                                        (
                                            [id] => 9
                                            [title] => Thriller
                                            [total_links] => 5
                                            [subcategories] => Array
                                                (
                                                )

                                        )

                                )

                        )

我需要一个递归函数,它将自下而上遍历subcategories,将total_links加在一起并更改其上方数组中total_links的值。

所以最后数组的total_links值为:

  • Books = 11
  • Jeffrey Archer = 8
  • 政治= 2
  • 惊悚= 5

最好不使用SPL功能(但如果没有别的办法则免费)。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

这是未经测试的,但应该这样做

function do_sums(&$array) {
    if (is_array($array['subcategories'])) {
        foreach ($array['subcategories'] as $category_array) {
            $array['total_links'] += do_sums($category_array); // recurse down first
        }
    }
    return($array['total_links']);
}

$your_array = array(...)

do_sums($your_array);

答案 1 :(得分:0)

代码:(Demo with extended sample data for testing

function sum_links(&$array){ // make $array modifiable by reference
    foreach($array as &$item){ // make $item modifiable by reference
        if(!empty($item['subcategories'])){  // only recurse if there are children in subcategories
            $item['total_links']+=array_sum(array_column(sum_links($item['subcategories']),'total_links'));
            // recursion returns full subarray, extract desired column data, add sum to the original value
        }
    }
    return $array;  // return the full & updated array
}

var_export(sum_links($array));

/* or because $array is modified by reference...
    sum_links($array);
    var_export($array);
*/