我有一组从数据库中提取的“答案”(多维数组)。我需要对每个值执行计算,以便我可以在图表上显示结果。
以下是一些示例输入:
$array = [
'A1' => [1 => 1, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
'A2' => [1 => 1, 2 => 1, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
'A3' => [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0]
];
我想使用这种逻辑从多维数组计算一个百分比值:
[A1] => Array( ([1]*100/sum([1]+[1]+[1]), [2]*100/sum([2]+[2]+[2]),..... )
[A2] => Array( ([1]*100/sum([1]+[1]+[1]), [2]*100/sum([2]+[2]+[2]),..... )
[A3] => Array( ([3]*100/sum([1]+[1]+[1]), [2]*100/sum([2]+[2]+[2]),..... )
我该怎么做?
我想要的输出:
[
'A1' => [1 => 50, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
'A2' => [1 => 50, 2 => 100, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
'A3' => [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0]
]
答案 0 :(得分:2)
啊,我看到你现在要做的事。
试试这个
$totals = array();
// First get our totals.
foreach ($mainArray as $subKey => $subArray) {
foreach ($subArray as $k => $v) {
// Add the column to our total.
$totals[$k] = isset($totals[$k]) ? $totals[$k] + $v : $v;
}
}
$answers = array();
// Then build our answers.
foreach ($mainArray as $subKey => $subArray) {
$answers[$subKey] = array();
foreach ($subArray as $k => $v) {
$answers[$subKey][$k] = ($v * 100) / $totals[$k];
}
}
print_r($answers);
答案 1 :(得分:0)
达斯汀的答案引起了很多除数为零的警告,所以我想我会花点时间写自己的答案。
由于示例输入数组具有相等长度的子数组,因此我不会理会isset()
,而只是相信从第一行调用array_column()
将访问所有可用值。
首先,声明foreach()
$v
,但未使用,因为array_column()
与其他垂直数据一起收集。 $column_totals
是一维求和的数组。
由于必须对多维输入数组的每个元素进行单独的计算,因此使用了两个循环。
在执行计算之前,请检查“当前值”和“列总和值”
为零值将启用0
的快速返回(并避免出现警告);否则,请使用OP的公式。
*对于不熟悉Order of Operations的人,公式中不需要括号,因为从左到右读取表达式将保持*
和/
的逻辑。 / p>
代码:(演示)
$array = [
'A1' => [1 => 1, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
'A2' => [1 => 1, 2 => 1, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
'A3' => [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0]
];
foreach (current($array) as $k => $v) {
$column_totals[$k] = array_sum(array_column($array, $k));
}
foreach ($array as $key => $row) {
foreach ($row as $k => $v) {
$result[$key][$k] = (!$v || !$column_totals[$k]) ? 0 : $v * 100 / $column_totals[$k];
}
}
var_export($result);
输出:
array (
'A1' =>
array (
1 => 50,
2 => 0,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
),
'A2' =>
array (
1 => 50,
2 => 100,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
),
'A3' =>
array (
1 => 0,
2 => 0,
3 => 0,
4 => 0,
5 => 0,
6 => 0,
7 => 0,
8 => 0,
9 => 0,
10 => 0,
),
)