Question

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.

Was it helpful?

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

OTHER TIPS

I assume that the first value in each array (in this case, "c") is the key that you use to determine if two rows are duplicates. In that case, you could replace the array you gave with an indexed array that looks like:

array(
    c=>array(5,6)
    test=>array(5,6)
    ...
)

Add your rows one by one, and test for whether the index you'd be using is already there, e.g., if in_array("c", array_keys($my_array)) . If the index isn't there, create a new array with that index. If it is there, instead iterate over the row and add each of its values to the corresponding column in the existing array. e.g., when you got to your second row with the key "c", you'd add its first value to $my_array["c"][0] and its second value to $my_array["c"][1].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top