我有一个数组
$data = array(
1 => array(1 => 11 ,2 => 21, 3 => 31),
2 => array(1 => 21 ,2 => 22),
3 => array(1 => 31 ,2 => 23, 3 => 32),
);
我想转变为
$data = array(
1 => array(1 => 11, 2 => 21, 3 => 31, 'Total' => 63),
2 => array(1 => 21, 2 => 22, 'Total' => 43),
3 => array(1 => 31, 2 => 23, 3 => 32, 'Total' => 83),
'Total' => array(1 => 63, 2 => 46, 3 => 63, 'Total' => 172),
);
一级和二级按键是动态的。在我的样本中,它们是 1,2,3,但也可能是 1 到 10。
我在 Stack Overflow 中找到的大多数答案都与数组中元素的总和或多维数组中不同键的总和有关,但我找不到任何在同一代码中解决这两个问题的答案,所以我认为分享可能会有用。
您想要的结果似乎不正确,通过手动进行计算,总数应该与您描述的不同。所以我假设你的例子错了,这就是你想要的实际结果:
$data = array(
1 => array(1 => 11 ,2 => 21, 3 => 31, 'Total' => 63),
2 => array(1 => 21 ,2 => 22, 'Total' => 43),
3 => array(1 => 31 ,2 => 23, 3 => 32, 'Total' => 86),
'Total' => array(1 => 63,2 => 66,3 => 63, 'Total' => 192),
);
所以你基本上想要两件事:
array_sum
完成的,您可以通过在 foreach
数组的第一层上执行 $data
来应用它。 有关 array_sum 的更多信息和官方 php 文档。key
的元素相加。为此,您可以使用一个简单的 foreach 来跟踪第二级键并对每个值求和生成的代码将这两点与以下逻辑结合起来:
Totals
数组第一级中的 $data
键array_sum
来获取 Total
Totals
数组中初始化相同的索引我添加了评论以使其更清楚:
// Initialize the 'Total' key in the first-level of the array. This will be populated in the foreach
$data['Total'] = [];
// Loop the first level of the array
foreach ($data as $key => $values) {
// Calculate the sum of the first level of the array, using array_sum
$data[$key]['Total'] = array_sum($data[$key]);
// Loop the second level of the array
foreach ($values as $index => $count) {
// For each INDEX, create the corresponding element of the Totals array
if (!isset($data['Total'][$index])) {
$data['Total'][$index] = 0;
}
// Sum this element $count in the Total array
$data['Total'][$index] += $count;
}
}
为了避免通过调用迭代数组函数以及嵌套
foreach()
来不必要地增加时间复杂度,请在嵌套循环结构中执行所有求和。
代码:(演示)
$data = [
1 => [1 => 11, 2 => 21 ,3 => 31],
2 => [1 => 21, 2 => 22],
3 => [1 => 31, 2 => 23 ,3 => 32],
];
foreach ($data as $k => $row) {
foreach ($row as $i => $v) {
$data[$k]['Total'] = ($data[$k]['Total'] ?? 0) + $v; // accumulate row total
$data['Total'][$i] = ($data['Total'][$i] ?? 0) + $v; // accumulate column total
}
$data['Total']['Total'] = ($data['Total']['Total'] ?? 0) + $data[$k]['Total']; // accumulate grand total
}
var_export($data);