2

恐怕我想做的事情根本不可能,但我希望你能帮助我找到解决这个问题的好方法。

我有以下 PHP 数组:

Array ( 
    [0] => Array ( [article] => 10.499-1 [operation] => KN_KABEL [date] => 31-05-2013 [hours] => 0 [quantity] => 1 ) 
    [1] => Array ( [article] => 10.499-1 [operation] => LAS_LABEL [date] => 31-05-2013 [hours] => 0 [quantity] => 1 ) 
    [2] => Array ( [article] => 10.499-1 [operation] => ASS_HARNES [date] => 04-06-2013 [hours] => 0 [quantity] => 1 ) 
    [3] => Array ( [article] => 10.499-1 [operation] => CONTROLE [date] => 07-06-2013 [hours] => 0 [quantity] => 1 ) 
    [4] => Array ( [article] => 24.030 [operation] => LAS_LABEL [date] => 04-06-2013 [hours] => 0 [quantity] => 1 ) 
    [5] => Array ( [article] => 24.030 [operation] => ZAGEN-RAIL [date] => 04-06-2013 [hours] => 0 [quantity] => 1 ) 
    [6] => Array ( [article] => 24.030 [operation] => KN_KABEL [date] => 04-06-2013 [hours] => 0 [quantity] => 1 ) 
    [7] => Array ( [article] => 24.030 [operation] => ASS_RAIL [date] => 05-06-2013 [hours] => 0 [quantity] => 1 ) 
    [8] => Array ( [article] => 791 070-6/GS/P [operation] => GS_UNIT [date] => 04-06-2013 [hours] => 0 [quantity] => 1 ) 
    [9] => Array ( [article] => 791 070-6/GS/P [operation] => PR_UNIT [date] => 04-06-2013 [hours] => 0 [quantity] => 1 ) 
    [10] => Array ( [article] => 791 070-6/GS/P [operation] => LAS_LABEL [date] => 04-06-2013 [hours] => 0 [quantity] => 1 ) 
    [11] => Array ( [article] => ESS-0834E/LE-CD200 [operation] => MAGAZIJN [date] => 10-06-2013 [hours] => 0 [quantity] => 1 ) 
    [12] => Array ( [article] => ESS-0834E/LE-CD200 [operation] => PR_UNIT [date] => 11-06-2013 [hours] => 0 [quantity] => 1 ) 
    [13] => Array ( [article] => ESS-0834E/LE-CD200 [operation] => LAB_PLAKKE [date] => 11-06-2013 [hours] => 0 [quantity] => 1 )
)  

我想要做的是计算每个日期(键“基准”)的小时总和(在这个例子中它们都是 0,但我仍然想这样做,因为这将在未来发生变化)。非常实用的是像 sql 这样的查询,SELECT SUM(hours) GROUP BY date但不幸的是,这不是 SQL。

有没有办法通过特定键(在本例中为“日期”)对我的数组进行分组(和排序),或者,如果没有,是否有其他方法可以获得我想要的结果?

编辑

我最近添加了一个关键的“部门”,应该按 to 分组。因此,我不仅要计算“小时”的总和,还要计算“数量”的总和

4

1 回答 1

2

只需为此创建简单的 foreach 即可。

$arr = array();

$sums = array();
foreach($arr as $k=>$v)
{
     if(!isset($sums[$v['date']][$v['department']]['hours'])) $sums[$v['date']][$v['department']]['hours'] = 0;
     if(!isset($sums[$v['date']][$v['department']]['quantity'])) $sums[$v['date']][$v['department']]['quantity'] = 0;
     $sums[$v['date']][$v['department']]['hours'] += $v['hours'];
     $sums[$v['date']][$v['department']]['quantity'] += $v['quantity'];
}
print_r($sums);

它将创建数组$sum,其中键是您的日期。如果值不存在,它将小时的值添加到 0,否则如果存在,它将添加到现有值。

编辑

适合 OP 需求。

于 2013-05-27T12:21:06.327 回答