我正在尝试使第一个foreach
循环中的选择框变粘:
我认为if
标记内应该有<option>
语句,如下所示:
if($selectedMake==$key){
echo selected='selected';
}
echo "<option im not sure how to properly enter it in here?>$key</option>"
//下面的代码开头:
$selectedMake = $_POST['make'];
$cars = array(
'Toyota'=>array(
'Corolla'=>array(
'image'=>'corolla.png',
'colour'=>'blue',
'transmission'=>'manual',
'doors'=>'2'
),
'Highlander'=>array(
'image'=>'highlander.png',
'colour'=>'silver',
'transmission'=>'auto',
'doors'=>'4'
),
),
'Mazda'=>array(
'RX7'=>array(
'colour'=>'blue',
'transmission'=>'manual',
'doors'=>'2'
),
'MX-5'=>array(
'colour'=>'red',
'transmission'=>'manual',
'doors'=>'2'
)
)
);
echo '<form method="post" action="cars.php">';
echo '<select name="make">';
foreach ($cars as $key => $value) {
echo "<option>$key</option>"; // This option tag needs to be made sticky
}
echo '</select>
<input type="submit" name="submit">
</form>
';
if (isset($_POST['submit'])) {
$selectedMake = $_POST['make'];
echo "<h1>$selectedMake</h1>";
foreach ($cars as $key => $value) {
if ($selectedMake == $key) {
foreach ($value as $key => $value) {
echo "<b>$key</b> <br>";
foreach ($value as $key => $value) {
if ($key == 'image') {
echo '<img src="imgs/'.$value.'" width="150px">';
} else {
echo "<li>$key: $value</li>";
}
}
echo "<br>";
}
}
}
} else {
echo "Not clicked";
}
echo '<pre>',print_r($cars),'</pre>';
?>
答案 0 :(得分:2)
如果通过粘性,则表示如果它与您拥有的值匹配则选择:
echo "<option".($selectedMake==$key ? " selected" : "").">$key</option>"
答案 1 :(得分:1)
<select name="make">
<?php
foreach (array_keys($cars) as $key) :
$selected = $key === $selectedMake ? ' selected' : '';
?>
<option<?= $selected ?>><?= htmlspecialchars($key) ?></option>
<?php endforeach ?>
</select>