Example of calculating two-dimensional array average value/group average value in php

Source: Internet
Author: User

Calculate the average value of an array. Calculate the average value of a two-dimensional array.

 The code is as follows: Copy code \$ Array = array (Array ('class' => 'A', 'value' => 3 ),Array ('class' => 'A', 'value' => 4 ),Array ('class' => 'B', 'value' => 5 ),Array ('class' => 'B', 'value' => 6))

Such arrays can be grouped by class key values to calculate the average value.
You can also calculate the total average value separately. The usage is as follows:

 The code is as follows: Copy code Array_avg (\$ array, 'class'); // returns a two-dimensional array.Array_avg (\$ array); // returns a one-dimensional array.// Returns a one-dimensional array after calculating the average value.// Parameter \$ avgby returns a two-dimensional array based on the average value of the specified fieldPrivate 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;}
Related Keywords:
Related Article E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD