array_walk_recursive() is a powerful built-in PHP function that recursively traverses every element in a multidimensional array and applies a specified callback function to it. It is ideal for scenarios where uniform processing of complex array structures is needed.
To demonstrate the usage of array_walk_recursive(), let's first define a multidimensional array containing student information, including their names, ages, and scores:
$students = array(
array(
'name' => 'Zhang San',
'age' => 18,
'scores' => array(80, 85, 90),
),
array(
'name' => 'Li Si',
'age' => 19,
'scores' => array(75, 78, 82),
),
array(
'name' => 'Wang Wu',
'age' => 20,
'scores' => array(90, 95, 88),
),
);
Next, we write a callback function that checks if the key is scores. If so, it calculates the average score and appends this value into the scores array:
function calculateAverage(&$value, $key)
{
if ($key === 'scores') {
$average = array_sum($value) / count($value);
$value['average'] = $average;
}
}
We use array_walk_recursive() to recursively traverse the multidimensional array and apply the callback function to each element:
<span class="fun">array_walk_recursive($students, 'calculateAverage');</span>
This adds an average key to each student's scores array, storing their average score.
By printing the modified array, we can clearly see the average scores have been added correctly:
<span class="fun">print_r($students);</span>
Sample output:
Array
(
[0] => Array
(
[name] => Zhang San
[age] => 18
[scores] => Array
(
[0] => 80
[1] => 85
[2] => 90
[average] => 85
)
)
[1] => Array
(
[name] => Li Si
[age] => 19
[scores] => Array
(
[0] => 75
[1] => 78
[2] => 82
[average] => 78.33333333333333
)
)
[2] => Array
(
[name] => Wang Wu
[age] => 20
[scores] => Array
(
[0] => 90
[1] => 95
[2] => 88
[average] => 91
)
)
)
This article explained how to use PHP's array_walk_recursive() function to recursively traverse multidimensional arrays and process their elements flexibly with callback functions. This approach enables developers to efficiently handle nested array data to meet complex application needs.