phparraysloopsarray-maparray-walk

PHP sum up array entries where two keys have the same value


I have the following array, in which I want to sum up the total_volume for all entries where the source and the target are the same.

Array (
[0] => Array
    (
        [source] => ABC
        [target] => DEF
        [total_volume] => 10
    )

[1] => Array
    (
        [source] => ABC
        [target] => GHI
        [total_volume] => 5
    )
[2] => Array
    (
        [source] => ABC
        [target] => DEF
        [total_volume] => 5
    )
)

The resulting array should look like this:

ResultArray (
[0] => Array
    (
        [source] => ABC
        [target] => DEF
        [total_volume] => 15
    )

[1] => Array
    (
        [source] => ABC
        [target] => GHI
        [total_volume] => 5
    )
)

My first thought would be to llop through the existing array and check via a nested loop over the ResultArray whether an entry with the matching source-target-pair already exists.

Is there an other way using array_walk() or a similar method?

Thanks in advance for your help!


Solution

  • not pretty but heres how I would do it with a nested foreach;

    $aStartingArray = array();
    $aStartingArray[] = array('source'=>'ABC', 'target' => 'DEF', 'total_volume' => 10); 
    $aStartingArray[] = array('source'=>'ABC', 'target' => 'GHI', 'total_volume' => 5); 
    $aStartingArray[] = array('source'=>'ABC', 'target' => 'DEF', 'total_volume' => 5); 
    
    
    $aSortedArray = array();
    
    foreach ($aStartingArray as $aArray) {
    
        $bSet = false;
    
        foreach ($aSortedArray as $iPos => $aTempSortedArray) {
    
            if(
                $aTempSortedArray['source'] == $aArray['source'] && 
                $aTempSortedArray['target'] == $aArray['target']){
    
                $aSortedArray[$iPos]['total_volume'] += $aArray['total_volume'];
    
                $bSet = true;
            }
    
        }
    
        if(!$bSet) {
    
            $aSortedArray[] = array(
                'source' => $aArray['source'], 
                'target' => $aArray['target'], 
                'total_volume' => $aArray['total_volume']
                );
        }
    }
    
    
    var_dump($aSortedArray);