按多维数组和计数值分组

时间:2016-12-22 10:26:07

标签: php multidimensional-array

我有这样的数组

[
    (int) 0 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 5,
    ],
    (int) 1 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 4,
    ],
    (int) 2 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 3,
    ],
    (int) 3 => [
        'Servloc' => '1',
        'WasteText' => 'Container2',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 3,
    ],
    (int) 4 => [
        'Servloc' => '2',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 2',
        'ContainerCount' => (int) 1,
    ],  
]

我需要根据来自ContainerCount的Servloc,WasteText,ContainerText PLUS SUM的相同值对此数组进行分组。

这个数组的结果应该是:

[
    (int) 0 => [
        'Servloc' => '1',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 12,
    ],
    (int) 3 => [
        'Servloc' => '1',
        'WasteText' => 'Container2',
        'ContainerText' => 'Container Type 1',
        'ContainerCount' => (int) 3,
    ],
    (int) 4 => [
        'Servloc' => '2',
        'WasteText' => 'Container1',
        'ContainerText' => 'Container Type 2',
        'ContainerCount' => (int) 1,
    ],  
]

我试图将第一个数组两次比较并比较这些值,如果它们相同则将结果放入另一个数组中。但它不起作用....

1 个答案:

答案 0 :(得分:2)

试试这个:

function groupArray($data) {
    $keys = array();

    foreach ($data as $child) {
        $key = $child['Servloc'] . $child['WasteText'] . $child['ContainerText'];

        if(!array_key_exists($key, $keys)) {
            // check if we already found objects with the same data, if not then we start with 0 as containercount
            $keys[$key] = array(
                'Servloc' => $child['Servloc'],
                'WasteText' => $child['WasteText'],
                'ContainerText' => $child['ContainerText'],
                'ContainerCount' => 0,
            );
        }

        $keys[$key]['ContainerCount'] += $child['ContainerCount'];
    }

    return array_values($keys);
}