Friday 25 May 2012

sum of one key/column of multi dimentional array

Some time we need to get sum of one key/column of a multdimentional array and need unique output similary to aggregated and grup by functions of mysql functions, here i have written a php function, this is my first post , so please tell me about this and if you can give a better algo for this, please share. I tried searching online but could not find one.

thanks

------------------------------------------------------------------------------------------------------------------------


function sumArraykey($array,$key){
 foreach($array as $first){
                $first[$key]="";
                $distinct[]=$first;
        }

        $unique = array_map("unserialize", array_unique(array_map("serialize", $distinct)));
        foreach($unique as $first){
                $sum=0;
                foreach($array as $second){
                        $val=$second[$key];
                        $second[$key]="";
                        $matchcounter=1;
                        if($second == $first){
                                $matchcounter++;
                                $sum+=$val;
                        }
                }
                $first[$key]=$sum;

                $return[]=$first;
        }
        return $return;
}
------------------------------------------------------------------------------------------------------------------------
Example use!!!


$test[]=array(0=>1,1=>2,2=>3,3=>4,4=>5,5=>6,6=>10);
$test[]=array(0=>1,1=>2,2=>3,3=>4,4=>5,5=>6,6=>10);
$test[]=array(0=>1,1=>2,2=>3,3=>4,4=>5,5=>6,6=>10);
$test[]=array(0=>3,1=>2,2=>3,3=>4,4=>5,5=>6,6=>10);
$test[]=array(0=>3,1=>2,2=>3,3=>4,4=>5,5=>6,6=>10);

$output=sumArraykey($test,6);
print_r($output);