前言
在项目开发的过程中有时候遇到树状结构数据计算从最末级节点依次计算到根节点中所有数据值的和,也就是计算子级节点数据相加等于父级节点,以此类推到根节点。 下面的方法使用到了递归查询计算的方法。 树状结构数据示例:
$tree = [
0 => [
"Code" => "1",
"PCode" => "",
"num" => 1,
"Price" => 2,
"children" => [
0 => [
"Code" => "1.1",
"PCode" => "1",
"num" => 1,
"Price" => 3,
],
1 => [
"Code" => "1.2",
"PCode" => "1",
"num" => 1,
"Price" => 4,
],
],
],
1 => [
"Code" => "2",
"PCode" => "",
"num" => 1,
"Price" => 2,
"children" => [
0 => [
"Code" => "2.1",
"PCode" => "2",
"num" => 1,
"Price" => 3,
],
1 => [
"Code" => "2.2",
"PCode" => "2",
"num" => 1,
"Price" => 3,
"children" => [
0 => [
"Code" => "2.2.1",
"PCode" => "2.2",
"num" => 1,
"Price" => 3,
],
],
],
],
],
];
这里计算节点的合价=单价*数量
function sum($data)
{
$aaa = 0;
foreach ($data as $item) {
if (isset($item['children']) && count($item['children']) > 0) {
$item['TotalPrice'] = sum($item['children']);
} else {
$item['TotalPrice'] = $item['num'] * $item['Price'];
}
$aaa += $item['TotalPrice'];
}
return $aaa;
}
对方法进行调用
$a = sum($tree);
print_r($a);
|