在PHP中设置默认值和记住选择框中的值的问题


Issue with setting the default value and remembering the values in select box in PHP

<form name="search" method="post" >
 Seach for: <input type="text" name="find" value="<?php echo (isset($_POST['find']) ? $_POST['find'] : ''); ?>" /> in
 <Select NAME="field">
 <Option VALUE="category1" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category1') ? 'selected="selected"': ''; ?>>category1</option>
 <Option VALUE="category2" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category2') ? 'selected="selected"': ''; ?>>category2</option>
 </Select>
 <input type="submit" name="search" value="Search" />
 </form>
 <?php
    if(!empty($_POST)){
        $options = array('category1'=> array('1' => 'dog', '2' => 'cat'), 'category2' =>array('1'=>'flower', '2'=>'grass'));
        $input = trim($_POST['find']);
        $category = $_POST['field'];
        $output = $options[$category][$input];
        echo $output;
}
?>

问题:

我怎样才能使category2成为选择框的默认值而不是category1?我试过了:

<Option VALUE="category2" <?php
echo (isset($_POST['field']) && $_POST['field'] === 'category2') ? 'selected="selected"' : '';
?> selected = "selected">category2</option>

但是它破坏了我的函数。输入1,选择category1,点击搜索后,选择框变为category2。那不是我想要的。我希望这个函数像这样执行:

    记住用户为输入字段和选择框设置的值。
  1. 为选择框设置默认值category2

我怎样才能做到这一点?

try default为cat2, select后为result

  <form method="post"> 
<Select name="field">
 <Option <?php  if(isset($_POST['field']) && $_POST['field'] == "category1")  echo 'selected="selected"'; ?> VALUE="category1" >category1</option>
 <Option <?php if ((isset($_POST['field']) && $_POST['field'] == "category2") OR empty($_POST['field']))  echo 'selected="selected'; ?> VALUE="category2" >category2</option>
 </Select>
 <input type="submit" />
 </form>

你可以这样使用

<form method="post"> 
<Select name="field">
 <Option VALUE="category2" >category2</option>
 <Option <?php  if($_POST['field'] == "category1")  echo 'selected="selected"'; ?> VALUE="category1" >category1</option>
 <Option <?php  if($_POST['field'] == "category3")  echo 'selected="selected"'; ?> VALUE="category3" >category3</option>
 </Select>
 <input type="submit" />
 </form>