tags:

views:

130

answers:

3

Hi there

I have to sum some arrays(an array of arrays). The structure of my arrays is like this:

Array([id]=>some_id, [name]=>some_name, [value]=>float_value)

I know that I have N arrays as the one before. I need to sum those with the same id.

any idea?

Example:
**

Array
(
    [id] => 1
    [name] => John00
    [value] => 0.9
)
Array
(
    [id] => 2
    [name] => Ann01
    [value] => 0.011
)
Array
(
    [id] => 3
    [name] => Ann
    [value] => 0.1
)


**

+1  A: 

I'm not completely sure what you are trying to do - I assume you want the sum grouped by the id for each distinct id, but I may be wrong.

<?php
//result array of sums
$sums = array();

//example data
$source = array(
    array('id'=>3, 'name'=>'some_name6', 'value'=>1.6),
    array('id'=>1, 'name'=>'some_name', 'value'=>1.4),
    array('id'=>1, 'name'=>'some_name2', 'value'=>7.2),
    array('id'=>2, 'name'=>'some_name3', 'value'=>4.4),
    array('id'=>1, 'name'=>'some_name4', 'value'=>1.2),
    array('id'=>2, 'name'=>'some_name5', 'value'=>1.4),
);

foreach ($source as $ar) {
    //create an entry for this id in the array of sums if does not exist.
    if (!isset($sums[ $ar['id'] ])) {
        $sums[ $ar['id'] ] = 0;
    }

    //add 'value' key to sum for that id
    $sums[ $ar['id'] ] += $ar['value'];
}

//sort by id
ksort($sums);

print_r($sums);

/* output:
Array
(
    [1] => 9.8
    [2] => 5.8
    [3] => 1.6
)
*/
Tom Haigh
you assumed right, but i get only the sum of the last id. I think i do a mistake somewhere. many thx
Ahmed Youssef
A: 

This looks like it's coming from a database, and the query is the best place to do such things. (if this is not data from a db, just ignore this answer).

SELECT id, SUM(value)
FROM YourTable
-- add your WHERE-constraints here
GROUP BY id;
soulmerge
no, those data are not coming from a db :(
Ahmed Youssef
A: 

Pseduo-code:

$totals = array();

function add($in)
{
   global $totals;
   if(!isset($totals($in['id']))
   {
      $totals[$in['id']] = $in['value'];
   }else
   {
      $totals[$in['id']] += $in['value'];
   }
}

array_walk('add',$input_array);

var_dump($totals);
Visage