我有两个阵列 一个
Array
(
[0] => Array
(
[a] => 30
[b] => 5
)
[1] => Array
(
[a] => 30
[b] => 5
)
[2] => Array
(
[a] => 30
[b] => 0
)
[3] => Array
(
[a] => 5
[b] => 5
)
[4] => Array
(
[b] => 15
[a] => 0
)
)
第二个数组
Array
(
[0] => Array
(
[a] => 207
[b] => 225
)
[1] => Array
(
[b] => 35
[a] => 0
)
[2] => Array
(
[a] => 35
[b] => 90
)
[3] => Array
(
[a] => 80
[b] => 140
)
[4] => Array
(
[a] => 40
[b] => 35
)
)
我想在相同的键上添加这两个数组,某些位置的键的顺序是不同的[a]和[b]
提前致谢
答案 0 :(得分:1)
假设这些数组具有相同的结构,这有望为您提供总数的第三个数组:
$array3 = Array();
reset($array1);
while (list($key) = each($array1)) {
reset($array1[$key]);
while (list($k,$v) = each($array1[$key])) {
$array3[$key][$k] = $v + $array2[$key][$k];
}
}
答案 1 :(得分:1)
这假设两个数组的长度始终相同,并且子数组始终只包含a
和b
索引。
$result = array();
foreach($arrayOne as $key => $value)
{
$result[] = array(
"a" => $value["a"] + $arrayTwo[$key]["a"],
"b" => $value["b"] + $arrayTwo[$key]["b"]
);
}
答案 2 :(得分:0)
我认为这是for循环和数组的课堂作业。
$array1 = array(....);
$array2 = array(....);
$finalArray = array();
$count = count($array1);
for (i = 0; $i < $count; $i++) {
$totalArray[a] = $array1[i][a] + $array2[i][a];
$totalArray[b] = $array1[i][b] + $array2[i][b];
$finalArray[] = $totalArray;
}