如何在键具有数组的多维数组中求和所有相同的键值?

时间:2018-09-12 15:49:54

标签: php arrays multidimensional-array sum

如何在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)

)

1 个答案:

答案 0 :(得分:0)

我可能会误解某件事,因为我没有得到与您显示的输出相同的输出,无论如何,这可能有助于实现您想要的答案

$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
        )
)