繁体   English   中英

按多维数组分组并计数值

[英]Group by multidimensional array and count values

我有这样的数组

[
    (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,
    ],  
]

我需要基于Servloc,WasteText,ContainerText的相同值以及来自ContainerCount的所有值对这个数组进行分组。

因此,此数组的结果应为:

[
    (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,
    ],  
]

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

尝试这个:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM