PHP foreach具有更多条件

时间:2016-02-26 06:54:57

标签: php

是否可以将foreach功能设置为超过2个条件。示例如下:

$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];

$string = 'NG';
foreach ($stat_cps as $url)
{
     if(strpos($string, $url) !== FALSE)
     {
          echo "One of the field is NG";
          return true;
     }
}

echo "All field is OK";

我想要的是:
如果$stat_cps$acc_idss包含NG,则echo "One of the field is NG";

在上面的代码中,它仅适用于$stat_cps

* stat_cps和acc_idss来自单选按钮形式。

任何人都可以提出建议吗?

4 个答案:

答案 0 :(得分:2)

具有array_mergeimplodestrpos功能的“单线”解决方案:

...
$hasNg = strpos("NG", implode(",", array_merge($stat_cps,$acc_idss)));
...

// check for 'NG' occurance
echo ($hasNg !== false)? "One of the field is NG" : "string 'NG' doesn't exists within passed data";

答案 1 :(得分:1)

您可以使用array_merge组合两个数组:

http://php.net/manual/en/function.array-merge.php

$stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$merged = array_merge($stat_cps,$acc_idss);
$string = 'NG';
foreach ($merged as $url)
{
     if(strpos($string, $url) !== FALSE)
     {
          echo "One of the field is NG";
          return true;
     }
}

这将删除重复的字符串键,但如果你只想要一个匹配,那么这看起来不应该是一个问题

从你发表评论尝试

 $stat_cps = $_POST['stat_cp'];
$acc_idss = $_POST['acc_ids'];
$merged = array_merge($stat_cps,$acc_idss);
$match = false;
$string = 'NG';
foreach ($merged as $url)
{
     if(strpos($string, $url) !== FALSE)
     {
          $match =  true;
     }
}

if($match){
       echo "One of the field is NG";
}else{
      echo "Everything is OK";
}

答案 2 :(得分:0)

HttpContext.Current.User.Identity.Name

答案 3 :(得分:0)

#header  user in_array()
    $stat_cps = $_POST['stat_cp'];
    $acc_idss = $_POST['acc_ids'];

    $string = 'NG';
    foreach ($stat_cps as $url)
    {
         if(in_array($string, $url) !== FALSE)
         {
              echo "One of the field is NG";
              return true;
         }
    }