我下面有两个包含字符串和数字的数组,
我只想保留一个字符串标题,并将每个键值的数值与另一个数组求和。
我已经尝试了许多在线可用的解决方案,但未找到所需的解决方案。
$array1 =
Array
(
[0] => Array
(
[0] => Out Of Warranty
[1] => Total Orders
[2] => Total Qty
[3] => Canceled Orders
)
[1] => Array
(
[0] => Today<br/>(04-26-2020)
[1] => 1
[2] => 1
[3] => 0
)
[2] => Array
(
[0] => Yesterday<br/>(04-25-2020)
[1] => 0
[2] => 0
[3] => 0
)
[3] => Array
(
[0] => This Week<br/>(04-20-2020 - 04-26-2020)
[1] => 22
[2] => 39
[3] => 0
)
[4] => Array
(
[0] => Last Week<br/>(04-13-2020 - 04-19-2020)
[1] => 7
[2] => 7
[3] => 0
)
[5] => Array
(
[0] => This Month<br/>(04-01-2020 - 04-26-2020)
[1] => 29
[2] => 46
[3] => 0
)
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-26-2020)
[1] => 30
[2] => 47
[3] => 0
)
)
$array2 =
Array
(
[0] => Array
(
[0] => Out Of Warranty
[1] => Total Orders
[2] => Total Qty
[3] => Canceled Orders
)
[1] => Array
(
[0] => Today<br/>(04-24-2020)
[1] => 10
[2] => 10
[3] => 0
)
[2] => Array
(
[0] => Yesterday<br/>(04-23-2020)
[1] => 7
[2] => 7
[3] => 0
)
[3] => Array
(
[0] => This Week<br/>(04-20-2020 - 04-24-2020)
[1] => 51
[2] => 51
[3] => 0
)
[4] => Array
(
[0] => Last Week<br/>(04-13-2020 - 04-19-2020)
[1] => 31
[2] => 31
[3] => 0
)
[5] => Array
(
[0] => This Month<br/>(04-01-2020 - 04-24-2020)
[1] => 93
[2] => 93
[3] => 0
)
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-24-2020)
[1] => 1281
[2] => 1281
[3] => 1
)
)
作为字符串的预期输出应仅使用一次,并且数字应相互添加。
例如,输出应为6索引,即array1和array2的6索引之和-
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-26-2020)
[1] => 1311
[2] => 1328
[3] => 1
)
如果您的数组总是按相同的顺序排序:
$newItems = [];
foreach ($array1 as $key => $item) {
$newItems[] = [
$item[0],
$item[1] + $array2[$key][1],
$item[2] + $array2[$key][1],
$item[3] + $array2[$key][1],
];
}
如果键以不同的顺序排列在数组中:
$newItems = [];
foreach ($array1 as $item) {
$name = $item[0]
$newItems[$name] = $item;
}
foreach ($array2 as $item) {
$name = $item[0]
$newItems[$name][1] += $item[1];
$newItems[$name][2] += $item[2];
$newItems[$name][3] += $item[3];
}
// apply array_values to get 0-indexed array
$newItems = array_values($newItems);