duancaiyi7567 2018-02-06 21:25
浏览 111
已采纳

计算嵌套数组对象中的值的平均值(PHP)

I have a problem here and I hope it's interesting enough to get help from the SO community. I have declared an array in my PHP code that looks like this:

$array = array:4 [▼
  0 => array:3 [▼
    "a" => 0.333
    "b" => 0.730
    "c" => 0.393
  ]
  1 => array:3 [▼
    "a" => 0.323
    "b" => 0.454
    "c" => 0.987
  ]
  2 => array:3 [▼
    "a" => 0.753
    "b" => 0.983
    "c" => 0.123
  ]
]

I am looking for a simpler way of processing all the array elements and producing a single array which has a mean value (average) of all the corresponding values i.e:

array (
  a => average of a's
  b => average of all b's
  c => average of all c's
)

This is the code I wrote below (which works):

$a = []; // Store all a values
$b = []; // Store all b values
$c = []; // Store all c values

for ( $i = 0; $i < count( $array ); $i ++ ) {
    // For each array, store each value in it's corresponsing array
    // Using variable variables to make it easy
    foreach ( $array[ $i ] AS $key => $val ) {
        $k    = $key;
        $$k[] = $val;
    };
}

// Create single array with average of all
$fa = array(
    'a' => array_sum($a)/count($a),
    'b' => array_sum($b)/count($b),
    'c' => array_sum($ac/count($c)
);

I have a feeling this is not the most efficient way to achieve this given the numerous PHP functions out there dealing with arrays. I want to know if there is a simpler way of doing it and how. Thanks guys!

  • 写回答

1条回答 默认 最新

  • dsjhejw3232 2018-02-06 21:36
    关注

    Assuming each sub-array has the same keys:

    foreach(array_keys($array[0]) as $key) {
        $result[$key] = array_sum($tmp = array_column($array, $key))/count($tmp);
    }
    
    • Get the keys from the first sub-array
    • Loop, extract those values from the main array and calculate
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条