php中计算二维数组平均值/分组平均值实例
计算数组平均值,二维数组平均值计算,分组计算平均值,代码如下:
- $array = array(
- array('class' => 'a', 'value' => 3),
- array('class' => 'a', 'value' => 4),
- array('class' => 'b', 'value' => 5),
- array('class' => 'b', 'value' => 6)
- )
这样的数组可分别以 class键值分组计算平均值,也可以单独计算总的平均值,用法如下:
- array_avg($array, 'class');//返回二维数组
- array_avg($array);//返回一维数组
- // 计算平均值 返回一维数组
- // 参数$avgby 按照指定字段算平均值 返回二维数组
- private function array_avg($array, $avgby = NULL) {
- $array_avg = array ();
- $number = count ( $array );
- foreach ( $array as $key => $value ) {
- if ($avgby) {
- $avg_key = $value[$avgby];
- $array_avg[$avg_key]['count'] ++;
- foreach ( $value as $k => $v ) {
- $array_avg[$avg_key][$k] += $v;
- }
- } else {
- foreach ( $value as $k => $v ) {
- $array_avg[$k] += $v;
- }
- }
- }
- $array = array ();
- foreach ( $array_avg as $key => $value ) {
- if ($avgby) {
- foreach ( $value as $k => $v ) {
- $array[$key][$k] = $v / $value['count'];
- }
- } else {
- $array[$key] = $value / $number;
- }
- }
- return $array;
- }