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

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.