PHP:三项验证比较

PHP:三项验证比较,php,validation,Php,Validation,我在主页上有3个特色产品面板,我正在为它写一个CMS页面。我正在尝试验证这些项目 它们通过三个元素、功能1、功能2和功能3进行选择。默认值为选择一个元素 我需要验证$\u POST,以确保用户没有为多个面板选择相同的产品 我已经计算出每个$\u POST都需要$\u POST['featuredN']>0,但我似乎找不到处理7个潜在结果的逻辑方法。使用逻辑表,其中1为设定值 1 2 3 ------- 0 0 0 1 1 1 1 0 0 0 1 0 0 0 1 1 1

我在主页上有3个特色产品面板,我正在为它写一个CMS页面。我正在尝试验证这些项目

它们通过三个
元素、
功能1
功能2
功能3
进行选择。默认值为
选择一个元素

我需要验证
$\u POST
,以确保用户没有为多个面板选择相同的产品

我已经计算出每个
$\u POST
都需要
$\u POST['featuredN']>0
,但我似乎找不到处理7个潜在结果的逻辑方法。使用逻辑表,其中1为设定值

1  2  3
-------
0  0  0
1  1  1
1  0  0
0  1  0
0  0  1
1  1  0
0  1  1
如果项目为0,则我不会更新它,但我希望用户能够在需要时更新单个项目

我无法找到一种逻辑方法来查看该项是否不是0,然后将其与另一项进行比较(如果该项也不是0)

到目前为止,我的同事建议将这些值相加。它用于查看是否不满足条件1
0


我有一种模糊的感觉,某种形式的递归函数可能是正确的,但我不能让我的大脑在这方面帮助我!对集体大脑也是如此!:)

为什么不使用一些简单的ifs

if($_POST['featured1'] != 0 && $_POST['featured1'] != $_POST['featured2'] && $_POST['featured1'] != $_POST['featured3']) {
    // do something with featured1
}
if($_POST['featured2'] != 0 && $_POST['featured2'] != $_POST['featured1'] && $_POST['featured2'] != $_POST['featured3']) {
    // do something with featured2
}
if($_POST['featured3'] != 0 && $_POST['featured3'] != $_POST['featured1'] && $_POST['featured3'] != $_POST['featured2']) {
    // do something with featured3
}

您可以尝试以下方法:

function getFeaturedProducts() {
  $featuredProducts = array();
  foreach (array('featured1', 'featured2', 'featured3') as $key) {
    $value = intval($_POST[$key]);
    if (in_array($value, $featuredProducts)) {
      // throw validation error!
      return false;
    }
    if ($value) $featuredProducts[$key] = $value;
  }
  return $featuredProducts;
}

$products = getFeaturedProducts();
if ($products === false) {
  echo "You can't select the same product twice!";
} else {
  // $products will have the same keys as $_POST, but will only contain ones 
  // we want to update, i.e. if feature1 was 0, it will not be present at this point
  foreach ($products as $key => $value) {
    // sample update
    mysql_query("UPDATE featured SET product_id=$value WHERE key=$key");
  }
}

如果要确保数组中有唯一的项(对于值大于0的每个项),可以执行以下操作

$selects = array(rand(0,2),rand(0,2),rand(0,2));

echo implode(",",$selects) . "\n";

function removeUnSelected($var) { return $var != 0; }
$selects = array_filter($selects,"removeUnSelected");

echo implode(",",$selects) . "\n";

if($selects == array_unique($selects))
{
    echo "true";
}

我还将阻止用户在提交表单之前选择相同的产品。您可以编写一个JS函数,从另外两个
select
s
onchange
中禁用所选选项。在此处阅读有关禁用的
选项的信息:是的,很简单。我不知道我怎么没做到。虽然为了验证,我需要生成错误消息的是
}else{
条件