2012-07-20 63 views
0

我有以下阵列:php in_array检查数组的最佳方式是什么?

if (empty($a)||empty($b)||empty($c)){ 
    if(empty($a)){ 
     $errors[]="a is empty"; 
    } 
    if(empty($b)){ 
     $errors[]="b is empty"; 
    } 
    if(empty($c)){ 
     $errors[]="c is empty"; 
      } 
}... 

我如何与if (in_array('??'; $errors))检查数组充满$a$b$c错误讯息?

我知道这样说:

$errors = array(
    'a' => 'Please enter a.', 
    'b' => 'Please enter b.', 
    'c' => 'Please enter c.' 
); 

在这里,我可以简单地用if (in_array('a'; $errors))检查是否存在对a或不是一些错误消息。我的问题是,我不仅有一个错误消息的a,b或c。所以,我期待像这样的方式,结合了这两种方法:

$errors = array(
     'a' => if (empty ($a) || $specific_error1_for_a || $specific_error2_for_a), 
     'b' => if (empty ($b) || $specific_error1_for_b || $specific_error2_for_b), 
     'c' => if (empty ($c) || $specific_error1_for_c || $specific_error2_for_c), 
    ); 

我正在寻找一种方式来搜索这些元素a,bc的失败消息的情况下,阵列errors[]

主要问题是,我想有一个变量或其他的东西,我可以搜索时使用in_array。为了得到更具体的:

我有我的每个输入字段的errorlayer。因此,我需要搜索整个阵列errors[]如果有一个特定的错误消息对特定输入字段:

<input type="text" id="a" name="a" value="<?php echo isset ($_POST['a'])? $_POST['a'] : ''; ?>" tabindex="10" autocomplete="off"/><?php if (**in_array(...., $errors)**):?><span class="error"><?php echo $errors['a'];?></span><?php endif;?> 

的问题是,就像我已经说过,我不是唯一一个错误消息的情况下更对于每个输入字段,这样我会有这样的事情:

(**in_array('a is empty' || 'a is too short' || 'a is too long' ..., $errors)**) 

这就是为什么我认为这将是更好的搜索只是一个这样的变量:

(**in_array($a, $errors)**) 

我真的很感激,如果有人可以给我这方面的建议。非常感谢。

+0

'array_intersect'可能有用(因为它类似于具有多个值的in_array),但我并不完全清楚你在这里要做什么。 – Brilliand 2012-07-20 10:00:45

+0

我更新了我的问题。希望现在清楚。 – bonny 2012-07-20 10:06:53

回答

1

array_intersect可以用来很像in_array多个值:

if(array_intersect($errors, array(
    'a is empty', 
    'specific_error1_for_a', 
    'specific_error2_for_a', 
))) { 
    // There is an error for a 
} 

不过,我会推荐不同的设计程序。如果存储在一个关联数组中的错误与开始,然后检查是否有给定变量的任何错误变得更加高效:

if(empty($a)){ 
    $errors['a'][]="a is empty"; 
} 
if(empty($b)){ 
    $errors['b'][]="b is empty"; 
} 
if(empty($c)){ 
    $errors['c'][]="c is empty"; 
} 

...

if(isset($errors['a'])) { 
    // There is an error for a 
} 
+0

好吧,更多维数组......我忘了这一点。我会尝试。感谢迄今。 – bonny 2012-07-20 10:21:40

+0

没关系,好​​像我在显示它们时遇到问题。我使用:<?php if(isset($ errors ['a'])):?><?php echo $ errors_2;?><?php endif;?>并使它具有可变性,我有:foreach($ errors为$ errors_1){foreach($ errors_1 as $ errors_2){echo $ errors_2;}} – bonny 2012-07-20 11:04:40

+0

在第一个实例中,您应该回显'$ errors ['a' ] [0]'或'implode('
',$ errors ['a'])''而不是'$ errors_2'。尽管(用foreach循环),但我没有发现第二个实例有什么问题;你能告诉我它做错了什么吗? – Brilliand 2012-07-20 12:22:25

相关问题