In PHP, the common way to find multi-dimensional arrays is recursively, as in the following code
$count =0; $sum = 0;
function Avgarr ($arr)
{
Global $sum, $count; Global variables
foreach ($arr as $value) {//Loop traversal array
if (Is_array ($value)) {
Avgarr ($value); Recursion
}
ElseIf (Is_int ($value)) {
$sum + + $value;
$count + +;
}
}
return $sum/$count; return average
}
Start by writing the above code, test an array, and the result is OK. Secretly pleased, thought is done. But how about a closer look? Can you continue to use this function after you have evaluated the average of an array? No, because the defined global variable has changed and cannot be reset automatically, after an array is finished with this function, it is discarded and cannot continue to be used. Unless you manually give $sum, $count zeroing. Wouldn't that be too much trouble? There is also this way to look at the code:
function Avgarr2 ($arr) {
$count =0; $sum = 0;
echo Avgarr ($arr);
}
Put the above function in another function, and use this function to reset $sum and $count each time. As a result, the function is universal.