Adding duplicate array rows in Php -
i create function in php adds rows of array 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 $col duplicate free array. so, in case,
combine_duplicates($test,0);
would me desired output. this.
<?php function combine_duplicates($array,$col) { $index = array(); foreach ($array $row) { $key = $row[$col]; if (!isset($index[$key])) { $index[$key] = $row; } else { ($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 here: http://codepad.org/mdhesqhi
Comments
Post a Comment