Search code examples
phparraysduplicatessummarization

Adding duplicate array rows in Php


I would like to create a function in PHP that adds together the rows of an array with a shared column value.

So input.

 $test = array(
    array("c", 5, 6),
    array("c", 2, 3),
    array("test", 5, 6)
 );

And output.

  $testduplicatefree = array(
    array("c", 7, 9),
    array("test", 5, 6)
    )
);

I'm thinking

function combine_duplicates($array,$col){
...
... 
return $duplicatefreearray; 
}

where the $col is the duplicate free array. So, in my case,

   combine_duplicates($test,0); 

would get me my desired output. Thanks for any help with this.


Solution

  • <?php
    
    function combine_duplicates($array,$col) {
        $index = array();
        foreach ($array as $row) {
            $key = $row[$col];
            if (!isset($index[$key])) {
                $index[$key] = $row;
            } else {
                for ($i = 0; $i < count($row); ++$i) {
                    if ($i != $col) {
                        $index[$key][$i] += $row[$i];
                    }
                }
            }
        }
    
        return array_values($index);
    }
    
    
    $array = array(
        array("c", 5, 6),
        array("c", 2, 3),
        array("test", 5, 6)
    );
    
    print_r(combine_duplicates($array, 0));
    

    Try it here: http://codepad.org/MDHEsqhi