sum and minus array function php
What is the easiest way to achieve:
a => 1, b => 0, c=> 3
a => 0, b => 10, c=> 1
Sum
a => 1, b =>10, c=>4
and
Minus
a => -1, b=> 10, c=> -2
I hope my examples make it clear... If you have any questions please leave a com开发者_开发百科ment
Sum:
$array1 = array('a' => 1, 'b' => 0, 'c' => 3);
$array2 = array('a' => 0, 'b' => 10, 'c' => 1);
$result = array();
foreach ($array1 as $key => $value)
$result[$key] = $value + $array2[$key];
You can implement the difference part similarly.
$sum = $minus = 0;
foreach ($arrays as $key=>$val)
{
$sum += $val;
$minus -= ($val*-1);
}
You want to add orsubstarct the values with same key.
Try to write function with array_walk
http://php.net/manual/en/function.array-walk.php
or put in a loop and add or substarct based on key.
精彩评论