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

如何获取多维数组中最大值对应的父级键并按分组处理

解决方案

方法一:遍历外层数组追踪最大值与父键

你的数组结构固定(外层键为父ID,每个元素下是指定分组的属性数组),无需递归遍历所有元素,分层处理更高效:

$values = [
    1 => [
        "Home" => [
            "Weight (kg)" => 4.0,
            "Length (cm)" => null,
            "Width (cm)" => null,
        ]
    ],
    2 => [
        "Home" => [
            "Weight (kg)" => 3.0,
            "Length (cm)" => 3.0,
            "Width (cm)" => null,
        ]
    ],
    3 => [
        "Home" => [
            "Weight (kg)" => 2.0,
            "Length (cm)" => 2.0,
            "Width (cm)" => null,
        ]
    ],
];

$targetGroup = "Home";
$maxValue = null;
$parentKeys = [];

foreach ($values as $parentId => $groupData) {
    // 跳过不存在目标分组的元素
    if (!isset($groupData[$targetGroup])) {
        continue;
    }
    // 遍历分组内属性,排除null值
    foreach ($groupData[$targetGroup] as $value) {
        if ($value === null) {
            continue;
        }
        // 更新最大值与对应父键
        if ($maxValue === null || $value > $maxValue) {
            $maxValue = $value;
            $parentKeys = [$parentId]; // 重置为当前父键
        } elseif ($value == $maxValue) {
            $parentKeys[] = $parentId; // 收集相同最大值的父键
        }
    }
}

// 输出结果
echo "最大值: " . $maxValue . "\n";
echo "对应的父级ID: " . implode(', ', $parentKeys);

方法二:用array_reduce简化逻辑

如果偏好函数式风格,可以通过array_reduce迭代外层数组,同步记录最大值和父键:

$targetGroup = "Home";

$result = array_reduce(array_keys($values), function ($carry, $parentId) use ($values, $targetGroup) {
    if (!isset($values[$parentId][$targetGroup])) {
        return $carry;
    }
    // 提取当前分组内的非null最大值
    $currentMax = max(array_filter($values[$parentId][$targetGroup], fn($v) => $v !== null));
    
    if ($carry['max'] === null || $currentMax > $carry['max']) {
        return [
            'max' => $currentMax,
            'parentIds' => [$parentId]
        ];
    } elseif ($currentMax == $carry['max']) {
        $carry['parentIds'][] = $parentId;
        return $carry;
    }
    return $carry;
}, ['max' => null, 'parentIds' => []]);

echo "最大值: " . $result['max'] . "\n";
echo "对应的父级ID: " . implode(', ', $result['parentIds']);

关键说明

  • 自动排除null值:避免无效值干扰最大值判断
  • 支持多最大值场景:如果多个父元素对应相同最大值,会收集所有对应父键;若只需第一个出现的,删除elseif分支即可
  • 分组可灵活切换:通过$targetGroup变量能快速更换要处理的分组名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:25:20