编写递归函数计算PHP数组中节点的得分
递归计算带权重的树形数组节点得分
需求说明
给定一个多级嵌套的PHP树形数组,需要实现递归函数calculateScores,对包含非空children的节点,通过子节点的result与对应weight加权求和,得到自身的result值。
原始数组
$array = [ [ 'result' => null, 'weight' => 50, 'children' => [ ['result' => 5, 'weight' => 50, 'children' => []], ['result' => 5, 'weight' => 50, 'children' => []] ] ], [ 'result' => 3, 'weight' => 50, 'children' => [] ], ];
待实现函数框架
function calculateScores(&$array) { } calculateScores($array);
期望结果
$array = [ [ 'result' => 5, 'weight' => 50, 'children' => [ ['result' => 5, 'weight' => 50, 'children' => []], ['result' => 5, 'weight' => 50, 'children' => []] ] ], [ 'result' => 3, 'weight' => 50, 'children' => [] ], ];
核心规则
- 节点存在非空
children时,必须通过子节点计算result,公式为:父节点result = 子节点1.result*(子节点1.weight/100) + 子节点2.result*(子节点2.weight/100) + ... - 支持任意深度的多级嵌套结构
- 无子节点的节点保持原有
result值不变
解决方案代码
function calculateScores(&$array) { foreach ($array as &$node) { // 先递归处理子节点,确保子节点的result已计算完成 if (!empty($node['children'])) { calculateScores($node['children']); // 计算当前节点的加权总分 $totalScore = 0; foreach ($node['children'] as $child) { $totalScore += $child['result'] * ($child['weight'] / 100); } $node['result'] = $totalScore; } } unset($node); // 释放循环引用,避免后续数组操作异常 } // 测试执行 $array = [ [ 'result' => null, 'weight' => 50, 'children' => [ ['result' => 5, 'weight' => 50, 'children' => []], ['result' => 5, 'weight' => 50, 'children' => []] ] ], [ 'result' => 3, 'weight' => 50, 'children' => [] ], ]; calculateScores($array); // 查看结果 print_r($array);
代码逻辑说明
- 使用引用传递数组,直接修改原数组,无需返回值
- 遍历每个节点时,优先递归处理子节点,保证多层嵌套的子节点会被先计算完成
- 对有子节点的节点,遍历所有子节点,按权重占比累加得分,最终赋值给当前节点的
result - 循环结束后释放节点引用,防止后续操作出现引用异常
内容的提问来源于stack exchange,提问作者Snake
相关产品推荐
相关产品推荐

