【问题标题】:Group by multidimensional array and count values按多维数组和计数值分组
【发布时间】:2016-12-22 10:26:06
【问题描述】:

我有这样的数组

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

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

【问题讨论】:

    标签: php multidimensional-array


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 2019-11-26
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      相关资源
      最近更新 更多