PHP's method for calculating the average value of an exclusive multi-dimensional array is just to traverse the array. Is there any other way to achieve this? Let's take a look at it. PHP's method for calculating the average value of an exclusive multi-dimensional array is just to traverse the array. Is there any other way to achieve this? Let's take a look at it.
Script ec (2); script
In php, a common method for finding a multidimensional, exclusive multi-dimensional array is recursion, as shown in the following code:
$ Count = 0; $ sum = 0;
Function avgarr ($ arr)
{
Global $ sum, $ count; // global variable
Foreach ($ arr as $ value) {// cyclically traverse the Array
If (is_array ($ value )){
Avgarr ($ value); // Recursion
}
Elseif (is_int ($ value )){
$ Sum + = $ value;
$ Count ++;
}
}
Return $ sum/$ count; // returns the average value.
}
At the beginning, I wrote the above Code and tested an array. The result is OK. I believe that success has been achieved. But what should I do? Can I continue to use this function after finding the average value of an array? No, because the defined global variables have changed and cannot be reset automatically. After an array is obtained using this function, it is useless and cannot be used any more. Unless $ sum and $ count are reset to zero each time. Isn't it too troublesome? In this way, check the Code:
Function avgarr2 ($ arr ){
$ Count = 0; $ sum = 0;
Echo avgarr ($ arr );
}
Place the above function in another function, and use this function to reset $ sum and $ count each time. In this way, the function is universal.