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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -