PHP递归调用数组值并用其执行指定函数的方法

本文实例讲述了PHP递归调用数组值并用其执行指定函数的方法,分享给大家供大家参考,具体分析如下:

以下为wordpress原代码,为了偷懒,简单修改一下以适用其它函数。

  1. /**
  2. * Navigates through an array and removes slashes from the values.
  3. *
  4. * If an array is passed, the array_map() function causes a callback to pass the
  5. * value back to the function. The slashes from this value will removed.
  6. *
  7. * @since 2.0.0
  8. *
  9. * @param mixed $value The value to be stripped.
  10. * @return mixed Stripped value.
  11. */
  12. function stripslashes_deep($value) {
  13. if ( is_array($value) ) {
  14. $value = array_map('stripslashes_deep', $value);
  15. } elseif ( is_object($value) ) {
  16. $vars = get_object_vars( $value );
  17. foreach ($vars as $key=>$data) {
  18. $value->{$key} = stripslashes_deep( $data );
  19. }
  20. } elseif ( is_string( $value ) ) {
  21. $value = stripslashes($value);
  22. }
  23. return $value;
  24. }
  25. <?php
  26. function function_deep($function,$value) {
  27. try {
  28. if(!function_exists($function)){
  29. $error = '"'.$function.'" is undefined';
  30. throw new Exception($error);
  31. }
  32. } catch (Exception $e) {
  33. echo 'Caught exception: ', $e->getMessage(), "\n";
  34. die();
  35. }
  36. if ( is_array($value) ) {
  37. $fun = Array();
  38. for($i=1;$i<=count($value);$i++){
  39. $fun[] = $function;
  40. }
  41. $value = array_map("function_deep",$fun, $value);
  42. } elseif ( is_object($value) ) {
  43. $vars = get_object_vars( $value );
  44. foreach ($vars as $key=>$data) {
  45. $value->{$key} = function_deep($function,$data );
  46. }
  47. } elseif ( is_string( $value ) ) {
  48. $value = call_user_func($function,$value);
  49. }
  50. return $value;
  51. }
  52. $arr = array(
  53. "I'm bean",
  54. "I'm bean",
  55. array("I'm bean","I'm bean")
  56. );
  57. var_dump(function_deep("addslashes",$arr));
  58. // 输出结果
  59. // array (size=3)
  60. // 0 => string 'I\'m bean' (length=9)
  61. // 1 => string 'I\'m bean' (length=9)
  62. // 2 =>
  63. // array (size=2)
  64. // 0 => string 'I\'m bean' (length=9)
  65. // 1 => string 'I\'m bean' (length=9)
  66. ?>