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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里