What’s the simplest way and uses less computing power to check if a multidimensional array has some equal values in the sub keys and, if is in this way, make the sum of that?
Look at the input. It’s something like this:
$array[] = ['number' => 1, 'values' => ['a' => 1, 'b' => 2]];
$array[] = ['number' => 2, 'values' => ['a' => 4, 'b' => 1]];
$array[] = ['number' => 2, 'values' => ['a' => 1, 'b' => 4]]; // same "number" as the previous so get the sum between "a" of the previous and "a" of this, the same for "b"
$array[] = ['number' => 2, 'values' => ['a' => 1, 'b' => 1]]; // same "number" as the previous so get the sum between "a" of the previous and "a" of this, the same for "b"
$array[] = ['number' => 3, 'values' => ['a' => 2, 'b' => 4]];
So the output should be
$array[0] : ['number' => 1, 'values' => ['a' => 1, 'b' => 2]];
$array[1] : ['number' => 2, 'values' => ['a' => 6, 'b' => 6]]; //a = 4 + 1 + 1 //b = 1 + 4 + 1
$array[2] : ['number' => 3, 'values' => ['a' => 2, 'b' => 4]];
To tell the truth I have trouble doing it even with simple foreach.
My brain can only go so far and no further.
$array_output = [];
foreach ($array as $k => $v){
foreach ($array as $kk => $vv){
if ($v['number'] == $vv['number']) {
// ????
}
}
}
Anyone help me?
Another question in the same question
How to do the same thing for
$array[] = ['number' => 1, 'a' => 1, 'b' => 2];
$array[] = ['number' => 2, 'a' => 4, 'b' => 1];
$array[] = ['number' => 2, 'a' => 1, 'b' => 4];
$array[] = ['number' => 2, 'a' => 1, 'b' => 1];
$array[] = ['number' => 3, 'a' => 2, 'b' => 4];
so how to get the sum for same variable number
for a
and b
variables?
2
Answers
checking result
gives me this
Using array functions. The idea is to build an array where the "number" is the key with
array_reduce
and then to remove these keys witharray_values
. This way you know easily if a number has been already encountered and if you have to sum or to define a new key.array_values
is finally used to remove these keys.demo
Note that this code is written for PHP >= 8.0. To make it compatible with older versions, remove the parameter labels in function calls (
callback:
,key:
,array:
, etc.).