合并两个多维数组:提取交集键并对对应字段值求和
解决两个多维数组共同键的数值求和问题
没问题,我来帮你搞定这个需求!要实现提取两个数组的共同键,并对对应字段求和的功能,咱们可以用PHP的数组函数配合循环来完成,步骤很清晰:
实现步骤
- 首先找出两个数组的共同键:用
array_intersect_key()函数可以直接获取两个数组都存在的键及其对应元素,或者用array_keys()配合array_intersect()只提取键名。 - 遍历这些共同键,分别对每个键对应的
library_count和crypt_count进行求和。 - 将求和后的结果存入新数组。
完整代码示例
// 定义第一个数组 $array1 = [ 'Fortitude' => ['library_count' => 0, 'crypt_count' => 7], 'Obtenebration' => ['library_count' => 6, 'crypt_count' => 11], 'Dementation' => ['library_count' => 1, 'crypt_count' => 0], 'Obfuscate' => ['library_count' => 0, 'crypt_count' => 2], 'Necromancy' => ['library_count' => 9, 'crypt_count' => 2], 'Celerity' => ['library_count' => 0, 'crypt_count' => 1], 'Redemption' => ['library_count' => 1, 'crypt_count' => 0], 'Dominate' => ['library_count' => 19, 'crypt_count' => 2], 'Auspex' => ['library_count' => 1, 'crypt_count' => 0], 'Potence' => ['library_count' => 1, 'crypt_count' => 2] ]; // 定义第二个数组 $array2 = [ 'Dominate' => ['library_count' => 19, 'crypt_count' => 7], 'Celerity' => ['library_count' => 0, 'crypt_count' => 6], 'Auspex' => ['library_count' => 1, 'crypt_count' => 2], 'Obtenebration' => ['library_count' => 6, 'crypt_count' => 0], 'Necromancy' => ['library_count' => 9, 'crypt_count' => 1], 'Potence' => ['library_count' => 1, 'crypt_count' => 1] ]; // 获取两个数组的共同键 $commonKeys = array_keys(array_intersect_key($array1, $array2)); // 初始化结果数组 $result = []; // 遍历共同键,计算求和 foreach ($commonKeys as $key) { $result[$key] = [ 'library_count' => $array1[$key]['library_count'] + $array2[$key]['library_count'], 'crypt_count' => $array1[$key]['crypt_count'] + $array2[$key]['crypt_count'] ]; } // 输出结果(可以用print_r或者var_dump查看) print_r($result);
运行结果
执行上述代码后,生成的新数组会是这样的:
Array ( [Obtenebration] => Array ( [library_count] => 12 [crypt_count] => 11 ) [Necromancy] => Array ( [library_count] => 18 [crypt_count] => 3 ) [Celerity] => Array ( [library_count] => 0 [crypt_count] => 7 ) [Dominate] => Array ( [library_count] => 38 [crypt_count] => 9 ) [Auspex] => Array ( [library_count] => 2 [crypt_count] => 2 ) [Potence] => Array ( [library_count] => 2 [crypt_count] => 3 ) )
这个方案逻辑清晰,用了PHP原生数组函数保证效率,而且代码可读性也不错,完全满足你的需求~
内容的提问来源于stack exchange,提问作者PrashJ
相关产品推荐
相关产品推荐

