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

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

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

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.