PHP:累积关联数组中的值

时间:2019-05-13 12:13:43

标签: php arrays accumulate

我想根据键的一部分在关联数组中累积值。

我已经测试了这个foreach循环,该循环在索引数组中可以正常工作:

$b = array();

foreach ($a as $key => $value) {
  if ($key > 0) {
    $b[$key] = $b[$key - 1] + $value;
  }
}

不过,我无法让它在关联数组中工作……

$a(节选)

Array ( 
    [2014-04-22|Paul] => 0 
    [2014-04-28|Paul] => 2 
    [2014-05-13|Paul] => 0
    [2014-06-03|Paul] => 1 
    [2014-06-12|Paul] => 0 
    [2014-08-11|Paul] => 1 
    [2014-08-28|Paul] => 3 
    [2012-05-09|John] => 1 
    [2012-08-29|John] => 2 
    [2012-09-05|John] => 0 
    [2012-09-13|John] => 1 
)

$b(期望的结果)

Array ( 
    [2014-04-22|Paul] => 0 
    [2014-04-28|Paul] => 2 
    [2014-05-13|Paul] => 2 
    [2014-06-03|Paul] => 3 
    [2014-06-12|Paul] => 3 
    [2014-08-11|Paul] => 4 
    [2014-08-28|Paul] => 7 
    [2012-05-09|John] => 1 
    [2012-08-29|John] => 3 
    [2012-09-05|John] => 3 
    [2012-09-13|John] => 4 
)

在期望的结果中,每个值都是'Paul',并且'John'(以及更多)被累加到前一个值。

2 个答案:

答案 0 :(得分:1)

使用array_walk,根据我要在下一个重置值的方式检查当前名称是否与姓氏相同。

$result = [];
$tempKey = '';
$arr = array_walk($arr, function($item, $key) use(&$result, &$tempKey, &$total){
    list($date, $name) = explode("|", $key); // explode key
    if(empty($tempKey) || $tempKey != $name){ // if empty or if conflict
        $tempKey = $name; // tempKey for reference
        $total = $item; // total reset to current value
    }else{
        $total += $item; // adding for same name
    }
    $result[$key] = $total; // putting calculated value
});

print_r($result);

输出

Array
(
    [2014-04-22|Paul] => 0
    [2014-04-28|Paul] => 2
    [2014-05-13|Paul] => 2
    [2014-06-03|Paul] => 3
    [2014-06-12|Paul] => 3
    [2014-08-11|Paul] => 4
    [2014-08-28|Paul] => 7
    [2012-05-09|John] => 1
    [2012-08-29|John] => 3
    [2012-09-05|John] => 3
    [2012-09-13|John] => 4
)

Demo

答案 1 :(得分:1)

您可以通过跟踪键的名称部分,并在获得新名称时重置总数来实现此目的:

deploy-only

输出:

$b = array();
$lastname = '';
foreach ($a as $key => $value) {
    list($d, $n) = explode('|', $key);
    if ($n == $lastname) {
        $total += $value;
    }
    else {
        $total = $value;
    }
    $b[$key] = $total;
    $lastname = $n;
}
print_r($b);

Demo on 3v4l.org