0

我有一个从数据库中提取的“答案”(多维数组)集合。我需要对每个值进行计算,以便可以在图表上显示结果。

这是一些示例输入:

$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]
]
4

2 回答 2

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);
于 2012-11-21T00:44:38.750 回答
1

达斯汀的答案是产生了很多除零警告,所以我想我会花时间写下自己的答案。

由于示例输入数组具有相等长度的子数组,因此我不会费心,isset()只需相信array_column()从第一行调用将访问所有可用值。

首先,foreach() $v声明但未使用,因为array_column()它与其他垂直数据一起收集。 $column_totals是和的一维数组。

因为必须对多维输入数组的每个元素进行单独的计算,所以使用了两个循环。

在执行计算之前,检查“当前值”和“列和值”是否为零值可以快速返回0(并避免警告);否则使用 OP 的公式。

*对于那些不熟悉运算顺序的人,公式中不需要括号,因为从左到右阅读表达式将保持与*and的逻辑/

代码:(演示)

$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,
  ),
)
于 2018-08-25T22:00:06.963 回答