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 field 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; } |