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

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -