The easiest way is to index your output array first using the year / month / day combination:
Note The above array of examples has all of its month keys with finite space. I just use month here with no spaces.
// Initialize output array... $out = array(); // Looping over each input array item foreach ($myArray as $elem) { // Initialize a new element in the output keyed as yyyy-mm-dd if it doesn't already exist if (!isset($out[$elem['year'] . "-" . $elem['month '] . "-" . $elem['day']])) { $out[$elem['year'] . "-" . $elem['month '] . "-" . $elem['day']] = array( // Set the date keys... 'year' => $elem['year'], 'month' => $elem['month '], 'day' => $elem['day'], // With the current value... 'value' => $elem['value'] ); } // If it already exists, just add the current value onto it... else { $out[$elem['year'] . "-" . $elem['month '] . "-" . $elem['day']]['value'] += $elem['value']; } } // Now your output array is keyed by date. Use array_values() to strip off those keys if it matters: $out = array_values($out);
Outputs (before calling array_values() ):
array(2) { '2011-5-13' => array(4) { 'year' => int(2011) 'month' => int(5) 'day' => int(13) 'value' => int(3) } '2011-5-14' => array(4) { 'year' => int(2011) 'month' => int(5) 'day' => int(14) 'value' => int(14) } }
Update:
To do the same with single-key dates (rather than 3 parts), it is easier without concatenation:
$myArray=array( array( 'date' => '2011-05-13', 'value' => 2 ), array( 'date' => '2011-05-14', 'value' => 5 ), array( 'date' => '2011-05-13', 'value' => 7 ), array( 'date' => '2011-05-14', 'value' => 3 ), ); foreach ($myArray as $elem) { // Initialize a new element in the output if it doesn't already exist if (!isset($out[$elem['date']])) { $out[$elem['date'] = array( // Set the date keys... 'date' => $elem['date'], // With the current value... 'value' => $elem['value'] ); } else { $out[$elem['date']]['value'] += $elem['value']; } }
source share