开发者

Operation value of multiple array that have the same key

I Have an 开发者_如何学编程array of array

array(4) {
      [0]=>
      array(3) {
        ["a"]=>float(1000)
        ["b"]=>float(3)
        ["c"]=>float(500)
      }
      [1]=>
      array(3) {
        ["a"]=>float(1000)
        ["b"]=>float(852)
        ["c"]=>float(500)
      }
      [2]=>
      array(3) {
        ["a"]=>float(1000)
        ["b"]=>float(5)
        ["c"]=>float(500)
      }
      [3]=>
      array(1) {
        ["e"]=>float(1000)
      }
    }

The result will sum all the value that the same keys,so result should be:

$result = 
  array(
      "a" =>3000,
      "b"=>900,
      "c"=>1500,
      "e"=>1000
  )

Anybody could help me todo this.

thanks.


Pseudo:

result <- new array                       # array holding result
foreach entry1 in array:                  # iterate outer array
    foreach entry2 in entry1:             # iterate each inner array
        if not exists result[entry2.key]: # if key is not already in result...
            result[entry2.key] = 0        # ... add key and set value to zero
        result[entry2.key] += value       # increment result for key with value from inner array

(I'll leave the implementation as an exercise for OP.)


The trick for this is ofcourse to do some sort of iteration over your data, using those string-keys as identifiers. One way of approaching it would be using 2 nested foreaches ( one over the container, one over the individual keys and collecting the data in a central array:

$results = array();
foreach ($array as $elements)
{
        foreach ($elements as $key => $value)
        {   
                if (!isset($results[$key]))
                        $results[$key] = 0;

                $results[$key] += $value;
        }   
}

A different way would be to have PHP iterate for you:

$results = array();

array_walk_recursive(
        $array,
        function($value, $key) use (&$results) {
                if (!isset($results[$key]))
                        $results[$key] = 0;

                $results[$key] += $value;
        }
);


This little function will do the job for you.

function SummarizeFosArray($array) {
    $results=array();
    foreach ($array as $a) {
      foreach ($a as $k=>$v) {
        $results[$k]+=$v;
      }
    }
    return $results;
}


Your code

$array = array(
        array('a' => 1000, 'b' =>3, 'c'=> 500),
        array('a' => 1000, 'b' =>852, 'c'=> 500),
        array('a' => 1000, 'b' =>5, 'c'=> 500),
        array('e' => 1000)
        );

$result = array();  

foreach($array as $arr)
{
    foreach($arr as $a => $val){
        $result[$a] += $val;
    }
}

echo "<pre>";
print_r($result);
echo "</pre>";  

Your Result

Array
(
    [a] => 3000
    [b] => 860
    [c] => 1500
    [e] => 1000
)


use array_walk_recursive() function. checkout the PHP manual for details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜