user3496603 user3496603 - 6 months ago 9
PHP Question

Sum the elements of an array key in a multidimensional array

This is my array

[Company] => Array
(
[0] => Array
(
[date] => 2016-05-28
[revenue] => 55
)

[1] => Array
(
[date] => 2016-05-28
[revenue] => 101
)

[2] => Array
(
[date] => 2016-05-29
[revenue] => 55
)

[3] => Array
(
[date] => 2016-05-29
[revenue] => 101
)

[4] => Array
(
[date] => 2016-05-30
[revenue] => 60
)

[5] => Array
(
[date] => 2016-05-30
[revenue] => 60
)

[6] => Array
(
[date] => 2016-05-31
[revenue] => 29
)

[7] => Array
(
[date] => 2016-05-31
[revenue] => 60
)

)


I need it to be summed up like this

[Company] => Array
(
[0] => Array
(
[date] => 2016-05-28
[revenue] => 151
)
*
*etc.
)


I've tried various methods by in vain. I've tried the below method but didn't work quite well

foreach($data as $key => $value) {
foreach ($value as $row) {


$res[$key][$row['date']] += $row['revenue'];
}
}

Answer

This should work, its not ideal as your looping over each array twice, as the array gets larger this will exponentially slow down.

$aStartingArray = array();
$aSortedArray   = array();

$aStartingArray[] = array('date'=>'2016-05-28', 'revenue' => 55);
$aStartingArray[] = array('date'=>'2016-05-28', 'revenue' => 101);
$aStartingArray[] = array('date'=>'2016-05-29', 'revenue' => 55);
$aStartingArray[] = array('date'=>'2016-05-29', 'revenue' => 101);
$aStartingArray[] = array('date'=>'2016-05-30', 'revenue' => 60);
$aStartingArray[] = array('date'=>'2016-05-30', 'revenue' => 60);
$aStartingArray[] = array('date'=>'2016-05-31', 'revenue' => 29);
$aStartingArray[] = array('date'=>'2016-05-31', 'revenue' => 60);

// loop through the initial array
foreach ($aStartingArray as $aArray) {

    // set flag to reference if its been dealt with
    $bSet = false;

    // foreach of the sorted values, check if the date matches an entry
    foreach ($aSortedArray as $iPos => $aTempSortedArray) {

        if( $aTempSortedArray['date'] == $aArray['date'] ){

            // match found, add revenue
            $aSortedArray[$iPos]['revenue'] += $aArray['revenue'];

            // set flag to illustrate a dealt with row
            $bSet = true;
        }

    }

    // if still hasnt been dealt with, go add it to the array
    if(!$bSet){
        $aSortedArray[] = array( 'date' => $aArray['date'], 'revenue' => $aArray['revenue'] );
    }

}

var_dump($aSortedArray);