array_walk_recursive()
遍历数组,把数组元素的键值和键名,传递给给回调函数处理,返回 boolean
同 arra_walk()的区别是,array_walk_recursive 会递归到数组的更深层次;遍历的顺序是从左到右按照书写的顺序,递归处理完第一个元素后,在一次处理后面的元素;
基础语法:
array_walk_recursive(array $array , callback $callback [, mixed $usedata = NULL]);
array $array ——被遍历的数组;
callback $callback ——接受数组元素的回调函数,第一个参数是 键值,第二个参数是键名,第三个参数是mixed $usedata;
mixed $usedata ——传递给函数的第三个参数;
语法结构1:
array_walk_recursive(array $array ,callback $callback)
没有多余数据参与的递归遍历;
实例:
$a_personal_info = [
'bill'=>array ('name'=>'bill','job'=>'worker','age'=>33),
'thomas'=>array ('name'=>'thomas','job'=>'driver','age'=>23)
];
function print_age ($v,$k){
if($k == 'name'){
echo $v.'的年纪是';
}else if($k == 'age'){
echo $v.'!<br/>';
}
}
array_walk_recursive($a_personal_info,'print_age');
语法结构2:
array_walk_recursive(array $array , callback $callback )
引用传递修改键值;
实例:
$a_employee = [
'bill'=>array ('name'=>'bill','job'=>'worker','age'=>33,'salar'=>3000),
'thomas'=>array ('name'=>'thomas','job'=>'driver','age'=>23,'salar'=>2000)
];
function change_salar(&$v,$k){
if($k == 'salar'){
$v *= 1.08;
}
}
array_walk_recursive($a_employee,'change_salar');
echo $a_employee['bill']['salar']
.'<br/>'
.$a_employess['thomas']['salar'];
#3240
#2160
语法结构3:
array_walk_recursive(array $array ,callback $callback,mixed $usedata)
传递另一个参数给回调函数,参与计算;
实例:
$a_employee = [
'bill'=>array ('name'=>'bill','job'=>'worker','age'=>33,'salar'=>3000,'diredate'=>2007),
'thomas'=>array ('name'=>'thomas','job'=>'driver','age'=>23,'salar'=>2000,'dirdate'=>2016)
];
function change_salar(&$v,$k,$ratio){
if($k == 'salar'){
$v *=$ratio
}
}
array_walk_recursive($a_employee,'change_salar',1.08);
echo $a_employee['bill']['salar']
.'<br/>'
.$a_employee['thomas']['salar'];
#3240
#2160
array_walk_recursive() 可以递归遍历
array_walk() 不可以递归遍历;
主要的区别就是,是否对多维数组进行递归遍历;