当前位置:网站首页>php中计算树状结构数据中的合计
php中计算树状结构数据中的合计
2022-07-02 06:23:00 【夜空の雪風】
前言
在项目开发的过程中有时候遇到树状结构数据计算从最末级节点依次计算到根节点中所有数据值的和,也就是计算子级节点数据相加等于父级节点,以此类推到根节点。
下面的方法使用到了递归查询计算的方法。
树状结构数据示例:
$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);//例子数据中的合计为13
边栏推荐
- Fe - eggjs combined with typeorm cannot connect to the database
- 微信小程序基础
- ModuleNotFoundError: No module named ‘jieba. analyse‘; ‘ jieba‘ is not a package
- Fe - weex uses a simple encapsulated data loading plug-in as the global loading method
- Error "list" object is not callable in Web automatic switching window
- Win电脑截图黑屏解决办法
- 如何调试微信内置浏览器应用(企业号、公众号、订阅号)
- 查询GPU时无进程运行,但是显存却被占用了
- Latex在VSCODE中编译中文,使用中文路径问题解决
- AWD learning
猜你喜欢

Latex参考文献引用失败 报错 LaTeX Warning: Citation “*****” on page y undefined on input line *

SQLI-LABS通關(less6-less14)

Vscode installation, latex environment, parameter configuration, common problem solving

Latex error: the font size command \normalsize is not defined problem solved

SQLI-LABS通关(less1)

【文献阅读与想法笔记13】 Unprocessing Images for Learned Raw Denoising

UEditor .Net版本任意文件上传漏洞复现

SQLI-LABS通关(less18-less20)

Implement strstr() II

Win电脑截图黑屏解决办法
随机推荐
Queue (linear structure)
[leetcode question brushing day 35] 1060 Missing element in ordered array, 1901 Find the peak element, 1380 Lucky number in matrix
js的防抖和节流
PHP Session原理简析
flex九宫格布局
js中map和forEach的用法
Promise中有resolve和无resolve的代码执行顺序
Cve - 2015 - 1635 (ms15 - 034) réplication de la vulnérabilité d'exécution de code à distance
默认google浏览器打不开链接(点击超链接没有反应)
Sqli-labs customs clearance (less15-less17)
Pytest (2) mark function
In depth study of JVM bottom layer (V): class loading mechanism
Stack (linear structure)
Explanation and application of annotation and reflection
Common function writing method and set get writing method for calculating attributes
20201002 vs 2019 qt5.14 developed program packaging
Vscode installation, latex environment, parameter configuration, common problem solving
js判断对象是否为空
Self cultivation of programmers - Reflection on job hunting
sqli-labs通关汇总-page2