Php 在递归生成的树中,如何将从子级到父级的值求和?
我有一个由递归函数构建的数组树。现在,我希望所有项目都包含通知/警告计数器。只是一个显示该项目有多少“通知”的数字 现在来谈谈问题。我想所有的项目,以显示从它自己和它的孩子的通知总数。但是递归函数是从上一级父级开始构建的,并向下运行。因此,计算通知数量的方法是错误的 像这样:Php 在递归生成的树中,如何将从子级到父级的值求和?,php,loops,recursion,tree,hierarchy,Php,Loops,Recursion,Tree,Hierarchy,我有一个由递归函数构建的数组树。现在,我希望所有项目都包含通知/警告计数器。只是一个显示该项目有多少“通知”的数字 现在来谈谈问题。我想所有的项目,以显示从它自己和它的孩子的通知总数。但是递归函数是从上一级父级开始构建的,并向下运行。因此,计算通知数量的方法是错误的 像这样: Item 1 (3) - - - Item 1.1 (1) - - - Item 1.2 (2) - - - - - - Item 1.2.1 (1) - - - - - - Item 1.2.2 (1) Item
Item 1 (3)
- - - Item 1.1 (1)
- - - Item 1.2 (2)
- - - - - - Item 1.2.1 (1)
- - - - - - Item 1.2.2 (1)
Item 2 (1)
- - - Item 2.1 (0)
- - - Item 2.2 (1)
<?php
public function tree($item_id)
{
global $wpdb;
$q = $wpdb->get_results("SELECT * FROM items WHERE parent_item_id = '".$item_id."'", "ARRAY_A");
foreach ($q as $key => $r)
{
$return[$key] = $r;
$return[$key]['notices'] = 1;
$return[$key]['children'] = $this->tree($r['item_id']);
}
return $return;
}
?>
这是我的递归函数(简化):
Item 1 (3)
- - - Item 1.1 (1)
- - - Item 1.2 (2)
- - - - - - Item 1.2.1 (1)
- - - - - - Item 1.2.2 (1)
Item 2 (1)
- - - Item 2.1 (0)
- - - Item 2.2 (1)
<?php
public function tree($item_id)
{
global $wpdb;
$q = $wpdb->get_results("SELECT * FROM items WHERE parent_item_id = '".$item_id."'", "ARRAY_A");
foreach ($q as $key => $r)
{
$return[$key] = $r;
$return[$key]['notices'] = 1;
$return[$key]['children'] = $this->tree($r['item_id']);
}
return $return;
}
?>
为什么不先调用树
函数,然后将通知
字段的总和添加到父字段的总和
$c_info = $this->tree($r['item_id']);
$sum = 0;
foreach ($c_info as $c_key => $c_data)
{
$sum += $c_data['notices'];
}
$return[$key]['children'] = $c_info;
$return[$key]['notices'] = 1 + $sum;
你能给我一个解决办法吗