如何在php

时间:2016-05-03 07:54:50

标签: php html forms select combinatorics

我的HTML代码中有3个SELECT元素,例如“省”,“区”和“市场”。我需要一个示例算法来检测已经完成选择的表单元素的组合。我正在考虑if条件的6种组合。

如何确定填充的SELECT元素与if条件的最小数量的组合?

到目前为止我的代码应该说明我想要实现的目标:

<select name="a">
  <option value="acity">a city</option>
</select>
<select name="b">
  <option value="bdistrict">b district</option>
</select>
<select name="c">
  <option value="cmarket">c market</option>
</select>
<?php
if($_POST["a"] != null and $_POST["b"] != null and $_POST["c"] != null)
  echo "aaaa";
elseif($_POST["a"] != null and $_POST["b"] != null)
  echo "bbb";
/*elseif ...*/
?>

感谢您的回复。

1 个答案:

答案 0 :(得分:0)

您可以将答案存储在数组中。下面的代码做了两个决定:选择了第一个连续选项的数量,以及包含无连接的任何组合。您可以存储函数,而不是存储值。

$combination = [ 'abc' => function() {return 'foo bar';} /* , ... */ ];
$combination['abc']();`

<!DOCTYPE html>
<html>
  <body>
    <form method="post">
      <select name="a">
        <option></option>
        <option value="acity">a city</option>
      </select>
      <select name="b">
        <option></option>
        <option value="bdistrict">b district</option>
      </select>
      <select name="c">
        <option></option>
        <option value="cmarket">c market</option>
      </select>
      <button type="submit">submit</button>
    </form>
<?php
$post_keys = [
  'a' => 'aaa',
  'b' => 'bbb',
  'c' => 'ccc'
];

$value = '[no valid selection]';

foreach($post_keys as $key => $val)
  if(isset($_POST[$key]) && '' !== $_POST[$key])
    $value = $val;
  else
    break;
?>
    <div>Form has been filled until: <?php echo $value;?>.</div>
<?
$combination = [
  ''    => 'nothing',
  'a'   => 'only a',
  'ab'  => 'c missing',
  'abc' => 'all',
  'ac'  => 'b missing',
  'b'   => 'only b',
  'bc'  => 'a missing',
  'c'   => 'only c'
];

$key_seq = '';
foreach($post_keys as $key => $val)
  if(isset($_POST[$key]) && '' !== $_POST[$key])
    $key_seq .= $key;

$value = $combination[$key_seq];
?>
    <div>Combination of a,b,c: <?php echo $value;?>.</div>
  </body>
</html>