$sum = 0
// foreach($tree as $key => $item) { //这句话有毒
foreach($tree as $key => &$item) {
if(isset($item['children'])) {
$oldPshuzi = $tree[$key]['Pshuzi']
$tree[$key]['Pshuzi'] = sumShuzi($item['children'], $updateData)
if($oldPshuzi != $tree[$key]['Pshuzi']) {
$updateData[$item['id']] = array($tree[$key]['Pshuzi'], $tree[$key]['Pname_ch'])
}
}
$sum += $tree[$key]['Pshuzi']
}
return $sum
}
$tree = json_decode('[{"id":"1","Pid":"0","Pname_ch":"\u6e20\u9053\u90e8","Pshuzi":"1638000","children":[{"id":"4","Pid":"1","Pname_ch":"\u9500\u552e\u4e8c\u90e8","Pshuzi":"895000","children":[{"id":"13","Pid":"4","Pname_ch":"\u5468\u7ecf\u7406","Pshuzi":"28","children":[{"id":"28","Pid":"13","Pname_ch":"\u6e56\u5357","Pshuzi":"158000"},{"id":"35","Pid":"13","Pname_ch":"\u65b0\u7586","Pshuzi":"19000"}]},{"id":"40","Pid":"4","Pname_ch":"\u9648\u7ecf\u7406","Pshuzi":"5000"}]}]}]', true)
//$tree是具有父子关系的数据树
sumShuzi($tree, $updateData)
foreach ($updateData as $id => $item) {
$sql = "update your_table set Pshuzi={$item[0]} where id={$id}"
mysqli_query($db, $sql) //$db是你的数据库连接结果
}
使用聚和函数 sum() 求和
select sum(money) from record t where t.name = ?
注意:t 是一个表的别名,比如 t.name 就是取 record 表中的name,使用 record.name 也可以,但就是太长了,所以起一个别名比较方便
扩展资料:
聚集函数是 AVG、COUNT、MAX、MIN 和 SUM,以下示例中描述了聚集函数的语法
aggregation-function ( [ ALL | DISTINCT ] expression )
或:COUNT( [ ALL | DISTINCT ] identification-variable )
或:COUNT( * )
在应用函数之前,DISTINCT 选项消除重复值。
参考资料来源:百度百科-聚集函数
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)