我有两个多维数组。这些是-
Array
(
[Fortitude] => Array
(
[library_count] => 0
[crypt_count] => 7
)
[Obtenebration] => Array
(
[library_count] => 6
[crypt_count] => 11
)
[Dementation] => Array
(
[library_count] => 1
[crypt_count] => 0
)
[Obfuscate] => Array
(
[library_count] => 0
[crypt_count] => 2
)
[Necromancy] => Array
(
[library_count] => 9
[crypt_count] => 2
)
[Celerity] => Array
(
[library_count] => 0
[crypt_count] => 1
)
[Redemption] => Array
(
[library_count] => 1
[crypt_count] => 0
)
[Dominate] => Array
(
[library_count] => 19
[crypt_count] => 2
)
[Auspex] => Array
(
[library_count] => 1
[crypt_count] => 0
)
[Potence] => Array
(
[library_count] => 1
[crypt_count] => 2
)
)
而且
Array
(
[Dominate] => Array
(
[library_count] => 19
[crypt_count] => 7
)
[Celerity] => Array
(
[library_count] => 0
[crypt_count] => 6
)
[Auspex] => Array
(
[library_count] => 1
[crypt_count] => 2
)
[Obtenebration] => Array
(
[library_count] => 6
[crypt_count] => 0
)
[Necromancy] => Array
(
[library_count] => 9
[crypt_count] => 1
)
[Potence] => Array
(
[library_count] => 1
[crypt_count] => 1
)
)
.. 这些数组有一些类似的键,例如“Celerity”。我想找到两个数组中的公共密钥,并将它们的库和密码计数相加,使它们成为一个数组。
您可以使用array\u intersect()
和array\u keys()
查找两个数组中使用的键。然后,迭代键以创建新数组:
$keys1 = array_keys($arr1);
$keys2 = array_keys($arr2);
$common_keys = array_intersect($keys1, $keys2) ;
$diff_keys = array_diff($keys1, $keys2);
$out = [];
foreach ($diff_keys as $diff) {
if (isset($arr1[$diff])) $out[$diff] = $arr1[$diff];
else $out[$diff] = $arr2[$diff];
}
foreach ($common_keys as $key) {
$out[$key] = $arr1[$key] ;
$out[$key]['library_count'] += $arr2[$key]['library_count'];
$out[$key]['crypt_count'] += $arr2[$key]['crypt_count'];
}
print_r($out);
产出:
Array
(
[Fortitude] => Array
(
[library_count] => 0
[crypt_count] => 7
)
[Dementation] => Array
(
[library_count] => 1
[crypt_count] => 0
)
[Obfuscate] => Array
(
[library_count] => 0
[crypt_count] => 2
)
[Redemption] => Array
(
[library_count] => 1
[crypt_count] => 0
)
[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
)
)