按周数汇总数组值

时间:2016-03-07 17:46:37

标签: php

您能否按周数列出以下销售数据

Array
(
    [0] => Array
    (
        [DATE] => 2015-03-06
        [store] => 18
        [weeknum] => 11
        [sales] => 10
    )
  [1] => Array
    (
        [DATE] => 2015-03-08
        [store] => 18
        [weeknum] => 11
        [sales] => 5
    )
  [2] => Array
    (
        [DATE] => 2015-03-09
        [store] => 18
        [weeknum] => 11
        [sales] => 5
    )

我想实现这样的目标

 [0] => Array
    (

        [store] => 18
        [weeknum] => 11
        [sales] => 20
    )

到目前为止,我已尝试过数组总和,但似乎无法正常工作

2 个答案:

答案 0 :(得分:1)

有许多不同的方法和答案(eg.)。 例如:

使用Array Reduce

$total_sales = array_reduce($items, function($carry, $item){
    $carry['store']   = $item['store'];
    $carry['weeknum'] = $item['weeknum'];
    $carry['sales']  += $item['sales'];
    return $carry;
}, []);

或使用Array column

$total_sales = array_sum(array_column($items, 'sales')); 

答案 1 :(得分:0)

只需遍历数组并将字段值添加到sum容器中。

我还添加了商店编号作为唯一标识符,以防有多个商店需要个人信息。如果您想要所有商店,只需使用$key = $weekNumber . $item['store'];更改$key = $weekNumber;

数据

$items = [
    [
        'DATE' => '2015-03-06',
        'store' => 18,
        'weeknum' => 11,
        'sales' => 10,
    ],
    [
        'DATE' => '2015-03-08',
        'store' => 18,
        'weeknum' => 11,
        'sales' => 5,
    ],
    [
        'DATE' => '2015-03-09',
        'store' => 18,
        'weeknum' => 11,
        'sales' => 5,
    ],
    [
        'DATE' => '2015-03-09',
        'store' => 18,
        'weeknum' => 12,
        'sales' => 5,
    ],
];

<强>代码

<?php

$storeWeekSums = [];

foreach ($items as $item) {
    // Save the key to refer to it later
    $weekNumber = $item['weeknum'];

    $key = $weekNumber . $item['store'];

    if (!isset($weekSums[$weekNumber])) {
        // The week and store does not already exist, let's create it with a value
        $storeWeekSums[$key] = [
            'store' => $item['store'],
            'weeknum' => $item['weeknum'],
            'sales' => $item['sales'],
        ];
    } else {
        // The week and store already exists, so we'll add to the current value instead
        $storeWeekSums[$key]['sales'] += $item['sales'];
    }
}

print_r($storeWeekSums);

<强>输出:

Array
(
    [1118] => Array
        (
            [store] => 18
            [weeknum] => 11
            [sales] => 5
        )

    [1218] => Array
        (
            [store] => 18
            [weeknum] => 12
            [sales] => 5
        )

)

DEMO