【问题标题】:How to validate array using foreach loop?如何使用 foreach 循环验证数组?
【发布时间】:2014-12-18 17:25:32
【问题描述】:

我有这个工作代码用于验证我的颜色选项。

 if ( !function_exists( 'sanitize_hex_color' ) ) {
     function sanitize_hex_color($color) {
        if ( '' === $color )
     return '';

  // 3 or 6 hex digits, or the empty string.
  if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) )
    return $color;

  return null;
  }
}

function validate_color_option($options){
//Check if hex color and sanitize
$options['wrapper_background_color'] = sanitize_hex_color($options['wrapper_background_color']);
$options['display_bg'] = sanitize_hex_color($options['display_bg']);

//Strips all html from input type text (NOT a color field)
$options['big_heading'] = wp_strip_all_tags($options['big_heading']);

return $options;

}//Function end

但由于我会有很多颜色字段,我想将我的颜色存储到一个数组中,执行一个 foreach 循环并通过 sanitize_hex_color 函数验证我的颜色选项。像这样的:

if ( !function_exists( 'sanitize_hex_color' ) ) {
     function sanitize_hex_color($color) {
        if ( '' === $color )
     return '';

  // 3 or 6 hex digits, or the empty string.
  if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) )
    return $color;

  return null;
  }
}

function validate_color_option($options){
  $colors = array(
  'color1' => $options['wrapper_background_color'],
  'color2' => $options['display_bg']
  );

   foreach($colors as $key => $val) {
   $colors[$key] = sanitize_hex_color($val);
   }

   //Strips all html from input type text (NOT a color field)
   $options['big_heading'] = wp_strip_all_tags($options['big_heading']);

   return $options;

}//Function end

说实话,我不知道如何使用 foreach 循环进行验证,然后返回我的值:(你们能帮帮我吗?谢谢!!

【问题讨论】:

    标签: php arrays wordpress validation foreach


    【解决方案1】:

    使用array_map()

    $colors = array(<colors>);
    array_map("sanitize_hex_color", $colors);
    

    它应该为每种颜色返回一个结果数组。 然后你以某种方式进一步处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2018-04-14
      相关资源
      最近更新 更多