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

如何对键名大小写不同但实质相同的PHP数组值求和

数组键名大小写不敏感求和方案

要实现键名相同但大小写不同的数组值求和,可通过统一键名大小写后累加数值的方式完成,以下是具体实现代码:

<?php 
$array = ['KEY'=> 5, 'TEST' => 3,'Test' => 10,'Key'=> 2];

$result = [];
foreach ($array as $key => $value) {
    $unifiedKey = strtoupper($key);
    if (isset($result[$unifiedKey])) {
        $result[$unifiedKey] += $value;
    } else {
        $result[$unifiedKey] = $value;
    }
}

$array = $result;

print_r($array);
/*
输出结果:
Array
(
    [KEY] => 7
    [TEST] => 13
)
*/
?>

实现说明

  • 使用strtoupper()将所有键名转为大写,消除大小写差异,确保同名键被归类
  • 遍历原数组时,对同一归类键的数值进行累加
  • 最终替换原数组为求和后的结果,键统一为大写格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:25:28