2011-11-16 41 views
0

如何迭代多維數組和字符串節點上的過濾器?我試圖創建一個簡單的方法來清理通過POST進入我的應用程序的數據,並認爲這將非常方便。如何迭代一個n深度數組來過濾字符串節點 - PHP

+0

可能重複(http://stackoverflow.com/questions/5593687/exclude-items-in-iterator) – Gordon

+0

的可能重複的[FOREACH與陣列陣列內] (http://stackoverflow.com/questions/5524227/php-foreach-with-arrays-within-arrays/5524267#5524267) – Gordon

+0

替代http://php.net/manual/en/function.filter-input-array .php和FILTER_CALLBACK – Gordon

回答

5

可以使用遞歸函數來遍歷數組和過濾的字符串組成部分。例如:的[排除項目在迭代]

function doFilter($arr) { 
    foreach ($arr as $key => $value) { 
     if (is_string($value)) { 
      $arr[$Key] = sanitize($value); 
     } else if (is_array($value)) { 
      $arr[$key] = doFilter($value); 
     } 
    } 
    return $arr; 
} 

function sanitize($str) { 
    // Perform necessary steps to sanitize $str 
    return $str; 
} 
0

您需要使用Recursion

function sanitizePost($post) { 
     if (is_array($post)){ 
      foreach ($post as $k => $p) { 
       $post[$k] = sanitizePost($p); 
      } 
     } else { 
      $post = sanatizeStringFunction($post); // may be use regex or something 
     } 

     return $post; 
    }