php--------递归函数

xiaoxiao2021-02-28  10

array_walk 有个原生递归函数 array_walk_recursive($arr, 'function', 'words'),但是 array_map 却没有对应的递归函数 array_map_recursive,

我们可以自定义一个:

function array_map_recursive($filter, $data) { $result = array(); foreach ($data as $key => $val) { $result[$key] = is_array($val) ? array_map_recursive($filter, $val) : call_user_func($filter, $val); } return $result; } 应用举例:

$arr = array( 'a' => '2', 'b' => array( 'cc' => 'wen', 'dd' => 'jian', 'ee' => 'bao' ) ); function func_a($value) { $value .= '_AAA'; return $value; } var_dump($arr); $arr = array_map_recursive('func_a', $arr); var_dump($arr); 其实吧,完全可以用  array_walk_recursive() 函数 实现该功能,如下代码所示: $arr = array( 'a' => '2', 'b' => array( 'cc' => 'wen', 'dd' => 'jian', 'ee' => 'bao' ) ); function func_b(&$value) { $value .= '_AAA'; } var_dump($arr); array_walk_recursive($arr, 'func_b'); var_dump($arr); 输出: array (size=2) 'a' => string '2' (length=1) 'b' => array (size=3) 'cc' => string 'wen' (length=3) 'dd' => string 'jian' (length=4) 'ee' => string 'bao' (length=3) array (size=2) 'a' => string '2_AAA' (length=5) 'b' => array (size=3) 'cc' => string 'wen_AAA' (length=7) 'dd' => string 'jian_AAA' (length=8) 'ee' => string 'bao_AAA' (length=7)
转载请注明原文地址: https://www.6miu.com/read-2050280.html

最新回复(0)