有什么最简单的方法并且使用较少的计算能力来检查多维数组在子键中是否具有一些相等的值,如果是,则计算其总和?
查看输入。它是这样的:
$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]];
所以输出应该是
$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]];
说实话,即使用简单的 foreach 我也很难做到这一点。
我的大脑只能思考到这个程度,不能再进一步。
$array_output = [];
foreach ($array as $k => $v){
foreach ($array as $kk => $vv){
if ($v['number'] == $vv['number']) {
// ????
}
}
}
有人能帮帮我吗?
同一问题中的另一个问题
如何做同样的事情$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];
number
那么如何对a
和变量计算相同变量的总和呢b
?