简体   繁体   中英

How do I determine multi-select combinations in php

I am having 3 SELECT elements such as "province", "district" and "market" in my HTML code. I need a sample algorithm to detect the combination on which form elements a selection has been done or not. I am thinking about 6 combinations of if conditions.

How can I determine the combination of filled SELECT elements with a minimum number of if conditions?

My code so far should illustrate, what I am trying to achieve:

<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 ...*/
?>

Thanks for reply.

You can store the answers in an array. The code below does 2 decisions: How many consecutive options from the first one has been selected and any combination inclusive none. Instead of storing values you could even store functions.

$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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM