我有一个多选项,它使用会话变量保存当前选定的选项。但是,当我取消选择所有选项时,最后选择的选项会保留。我该如何解决?这是我的代码:
<!DOCTYPE html>
<?php
session_start();
if(isset($_POST['occupation']))
$_SESSION['occupation'] = $_POST['occupation'];
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<h2>Industy</h2>
<select name="occupation[]" multiple >
<?php
$occ = array("Accounting", "Education", "Healthcare", "Information Technology", "Retail", "Sales");
$len = count($occ);
for($i = 0; $i<$len; $i++ )
{
if(in_array($occ[$i], $_SESSION['occupation']))
echo '<option value="' . $occ[$i] . '" selected>' . $occ[$i] .'</option>';
else
echo '<option value="' . $occ[$i] . '" >' . $occ[$i] .'</option>';
}
?>
</select>
<br/><br/>
<button type="submit" value="Search" class="my-button" name="search_button" >Search</button>
</form>
</body>
</html>
答案 0 :(得分:0)
只需添加您的代码,如果您提交时没有任何值,只需将会话数组覆盖为空。
以下是这个想法:
<?php
session_start();
$occ = array("Accounting", "Education", "Healthcare", "Information Technology", "Retail", "Sales");
if (empty($_SESSION['occupation'])) { // initialize
$_SESSION['occupation'] = array();
}
if(isset($_POST['search_button'])) { // if submitted
// set session occupation else just set empty
$_SESSION['occupation'] = !empty($_POST['occupation']) ? $_POST['occupation'] : array();
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<h2>Industy</h2>
<select name="occupation[]" multiple>
<?php foreach ($occ as $o) { ?>
<option value="<?php echo $o; ?>" <?php echo in_array($o, $_SESSION['occupation']) ? 'selected' : ''; ?>>
<?php echo $o; ?>
</option>
<?php } ?>
</select>
<br/><br/>
<button type="submit" value="Search" class="my-button" name="search_button" >Search</button>
</form>
</body>
</html>