php - Calculate the sum of elements if have the same date -
i have question, have array :
array ( [0] => array ( [date] => 2015-07-07 [nb] => 12 ) [1] => array ( [date] => 2015-07-10 [nb] => 6 ) [2] => array ( [date] => 2015-07-07 [nb] => 8 ) [3] => array ( [date] => 2015-07-09 [nb] => 48 ) [4] => array ( [date] => 2015-07-09 [nb] => 42 ) }
but want obtain this:
array ( [0] => array ( [date] => 2015-07-07 [nb] => 20 ) [1] => array ( [date] => 2015-07-09 [nb] => 90 ) [2] => array ( [date] => 2015-07-10 [nb] => 6 ) }
the idea if in array exist multiple dates [nb] must added up.
i tried this:
foreach($atotalrows $k=>$row){ if($row[$k]['date'] == $row[$k+1]['date']){ $row[$k]['nb'] = $row[$k]['nb'] + $row[$k+1]['nb'] } }
but not work solution, can me please? thx in advance
no, work if sort date first.... try building like:
$aggregatearray = array(); foreach($atotalrows $row) { if(!array_key_exists($row['date'], $aggregatearray) { $aggregatearray[$row['date']] = 0; } $aggregatearray[$row['date']] += $row['nb'] }
which give like:
array( ['2015-07-07'] => 20 ['2015-07-10'] => 90 ['2015-07-11'] => 6 )
and can restructure if necessary
Comments
Post a Comment