选项属性<option tags =“”in =“”a =“”foreach =“”loop

时间:2018-03-04 14:31:31

标签: php arrays associative

=“”

我正在寻找在这里我可以努力工作的一些指导。 我有一个带有以下选项的关联数组:

$options_format [] = [
    'name' => 'Audio',
    'type' => 'Audio',
];

$options_format [] = [
    'name' => 'EBook',
    'type' => 'EBook',
];

$options_format [] = [
    'name' => 'Hardcover',
    'type' => 'Hardcover',
];

$options_format [] = [
    'name' => 'Paperback',
    'type' => 'Paperback',
];

每个循环的以下内容然后遍历数组以输出html:

<?php 
    $select = 'selected';
    foreach ($options_format as $key => $value) {
        echo '<option value="' . $value['name'] . '"' . (isset($format) && $format == $value['name']) {  "$select"  };
        echo ">" . $value['name'];
        echo '</option>' . "\n";
    }
?>

$format变量保存已选择的值,然后检查是否设置了$format变量。但我想要做的是,如果表单条目有验证错误,它将保留用户之前选择的值。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

$select = 'selected';
foreach ($options_format as $key => $value) {
    echo '<option value="' . $value['name'] . '"' . ((isset($format) && $format == $value['name']) ? "$select" : "")  ;
    echo ">" . $value['name'];
    echo '</option>' . "\n";
}

编写三元运算符的方式:

((isset($format) && $format == $value['name']) ? "$select" : "")

假设$format包含$_POST['select_field_name']的值。

答案 1 :(得分:0)

尝试此操作,您可以使用所需的值更改$ format。

<?php

$options_format [] = [
    'name' => 'Audio',
    'type' => 'Audio',
];

$options_format [] = [
    'name' => 'EBook',
    'type' => 'EBook',
];

$options_format [] = [
    'name' => 'Hardcover',
    'type' => 'Hardcover',
];

$options_format [] = [
    'name' => 'Paperback',
    'type' => 'Paperback',
];
$format = "Hardcover";
 $select = 'selected';
echo "<select>";

    foreach ($options_format as $key => $value) {
        echo "<option value='".$value['name'] ."' ";
        if($value['name']==$format) 
           echo $select. ">";

        else
            echo ">";

       echo $value['name'] .'</option>' . "\n";
    }
echo "</select>";

?>