数组值的总和

时间:2015-03-11 11:13:48

标签: php arrays

$weektotnos = array(); 
$sums = 0;
foreach($reportlists as $reportlist)
{       
    foreach($reportlist as $reps)
    {
        $sums+=$reps['total_working_days'];      
        $weektotnos[date('W',strtotime($reps['work_date']))] = $sums;
    }
} 

得到了这个,

Array ( [10] => 5 [11] => 13 ) 

但需要这种格式数组,

Array ( [10] => 5 [11] => 8 ) 

感谢Advance!

2 个答案:

答案 0 :(得分:0)

需要PHP> = 5.5

$array1 = [10, 10, 10, 10, 11, 11];
$array2 = [2,  1,  2,  0,  2,  6];

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($array1));
$mi->attachIterator(new ArrayIterator($array2));
$newArray = [];
foreach($mi as list($key, $value)) {
    $newArray[$key] = isset($newArray[$key]) ?  $newArray[$key] + $value : $value;
}
var_dump($newArray);

对于早期版本的PHP,您可以使用

$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC);
$mi->attachIterator(new ArrayIterator($array1), 'key');
$mi->attachIterator(new ArrayIterator($array2), 'value');
$newArray = [];
foreach($mi as $details) {
    extract($details);
    $newArray[$key] = isset($newArray[$key]) ?  $newArray[$key] + $value : $value;
}

答案 1 :(得分:0)

    $sumArray = array();
    $sumval = 0;
    foreach ($reportlists as $k=>$subArray) {        
      foreach ($subArray as $id=>$value) {

        if (isset($sumArray[date('W',strtotime($value['work_date']))]))
        {
        $sumArray[date('W',strtotime($value['work_date']))] += $value['total_working_days'];
        }
        else
        {
        $sumArray[date('W',strtotime($value['work_date']))] = $value['total_working_days'];
        }   
      }
    }

结果:

数组([10] => 5 [11] => 43)

参考:

http://laravel.io/bin/JxoRa