如何在键具有数组的多维数组中求和所有相同的键值?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在键具有数组的多维数组中求和所有相同的键值?相关的知识,希望对你有一定的参考价值。
如何在php中通过关联键添加所有列值?请注意,[1GB]键是动态的
Array(
[0] => Array
(
[1GB] => array(1,2,1,3)
[2GB] => array(1,2,1,3)
)
[1] => Array
(
[1GB] => array(1,2,1,3)
[2GB] => array(1,2,1,3)
[5GB] => array(1,2,1,3)
)
[2] => Array
(
[3GB] => array(1,2,1,3)
[4GB] => array(1,2,1,3)
)
[2] => Array
(
[3GB] => array(1,2,1,3)
[4GB] => array(1,2,1,3)
)
)
期望的结果:
Array(
[1GB] => array(2,3,2,6)
[2GB] => array(2,3,2,6)
[3GB] => array(1,2,1,3)
[4GB] => array(1,2,1,3)
[5GB] => array(1,2,1,3)
)
答案
我可能误解了一些东西,因为我没有得到你所展示的相同输出,无论如何,它可能有助于实现你想要的答案
$dataset = [
[
['1GB' => [1, 2, 1, 3]],
['2GB' => [1, 2, 1, 3]],
],
[
['1GB' => [1, 2, 1, 3]],
['2GB' => [1, 2, 1, 3]],
['5GB' => [1, 2, 1, 3]],
],
[
['3GB' => [1, 2, 1, 3]],
['4GB' => [1, 2, 1, 3]],
],
[
['3GB' => [1, 2, 1, 3]],
['4GB' => [1, 2, 1, 3]],
]
];
$resume = [];
foreach ($dataset as $data) {
foreach ($data as $item) {
foreach ($item as $key => $value) {
if (!array_key_exists($key, $resume)) {
$resume[$key] = $value;
} else {
foreach ($value as $index => $number) {
$resume[$key][$index] += $number;
}
}
}
}
}
ksort($resume);
print_r($resume);
产量
Array
(
[1GB] => Array
(
[0] => 2
[1] => 4
[2] => 2
[3] => 6
)
[2GB] => Array
(
[0] => 2
[1] => 4
[2] => 2
[3] => 6
)
[3GB] => Array
(
[0] => 2
[1] => 4
[2] => 2
[3] => 6
)
[4GB] => Array
(
[0] => 2
[1] => 4
[2] => 2
[3] => 6
)
[5GB] => Array
(
[0] => 1
[1] => 2
[2] => 1
[3] => 3
)
)
以上是关于如何在键具有数组的多维数组中求和所有相同的键值?的主要内容,如果未能解决你的问题,请参考以下文章
使用带有 sql 的键值对搜索 php 多维关联数组,例如 '%LIKE%' 构造
循环遍历多维数组以生成新数据并在节点 js / javascript 中追加新的键值