douwulu2576 2012-11-21 00:12
浏览 24
已采纳

如何使用列数据的总和对多维数组的每个值进行数学运算?

I have a collection of "answers" (multi-dimensional array) which is extracted from a database. I need to perform a calculation on each value so that I can show the results on a graph.

Here is some sample input:

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

I want to calculate a percentage value from the multidimensional array using this kind of logic:

[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]),..... )

How can I do this?

My desired output:

[
  '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]
]
  • 写回答

2条回答 默认 最新

  • doxrxwn2252 2012-11-21 00:44
    关注

    Ahh, I see what you're trying to do now.

    Try this

    $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条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建