PHP basic problem two-dimensional array summation!
Array:
$a = Array (Array ("A" => "AA", "A1" =>1, "A2" =>1), Array ("a" => "BB", "A1" =>2, "A2" =>2), Array ("a" => cc "," A1 "=>3," A2 "=>3),
Array ("A" => "AA", "A1" =>1, "A2" =>1), Array ("a" => "BB", "A1" =>5, "A2" =>5))
Sum of elements with the same first key value
Results
$r = Array (Array ("A" => "AA", "A1" =>2, "A2" =>2), Array ("a" => "BB", "A1" =>7, "A2" =>7), Array ("a" => cc "," A1 "=>3," A2 "=>3));
------Solution--------------------
$a = Array (
Array ("A" => "AA", "A1" => 1, "A2" => 1),
Array ("a" => "BB", "A1" => 2, "A2" => 2),
Array ("A" => "CC", "A1" => 3, "A2" => 3),
Array ("A" => "AA", "A1" => 1, "A2" => 1),
Array ("a" => "BB", "A1" => 5, "A2" => 5),
);
$res = Array ();
foreach ($a as $r) {
if (! isset ($res [$r [' a ']]) $res [$r [' a ']] = $r;
else {
$res [$r [' A ']][' A1 '] + + = $r [' A1 '];
$res [$r [' A ']][' A2 '] + + = $r [' A2 '];
}
}
Print_r (Array_values ($res));
Array
(
[0] => Array
(
[A] => AA
[A1] => 2
[A2] => 2
)
[1] => Array
(
[A] => BB
[A1] => 7
[A2] => 7
)
[2] => Array
(
[A] => cc
[A1] => 3
[A2] => 3
)
)