You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写递归函数计算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);

代码逻辑说明

  1. 使用引用传递数组,直接修改原数组,无需返回值
  2. 遍历每个节点时,优先递归处理子节点,保证多层嵌套的子节点会被先计算完成
  3. 对有子节点的节点,遍历所有子节点,按权重占比累加得分,最终赋值给当前节点的result
  4. 循环结束后释放节点引用,防止后续操作出现引用异常

内容的提问来源于stack exchange,提问作者Snake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:51:02