在php中设置选择值的最佳方法

时间:2018-06-29 12:01:47

标签: php html laravel laravel-blade

我正在寻找一种基于数据库数据来用php设置html动态值的好方法。当前看起来像这样:

<select class="form-control" name="displayNavigation" id="displayNavigation">
    @if(isset($site['displayNavigation']) and $site['displayNavigation'] == 1)
        <option value="1" selected>Yes</option>
        <option value="0">No</option>
    @elseif(isset($site['displayNavigation']) and $site['displayNavigation'] == 0)
        <option value="1">Yes</option>
        <option value="0" selected>No</option>
    @else
        <option value="1">Yes</option>
        <option value="0">No</option>
    @endif
</select>

我认为这不是为具有超过10个选项的选择列表设置值的正确方法。

还有另一种方法吗?

4 个答案:

答案 0 :(得分:2)

如果有帮助,请尝试以下代码

<select class="form-control" name="displayNavigation" id="displayNavigation">   
    <option value="1" @if(isset($site['displayNavigation']) and $site['displayNavigation'] == 1) selected @endif>Yes</option>
    <option value="0" @if(isset($site['displayNavigation']) and $site['displayNavigation'] == 0) selected @endif>No</option>    
</select>

答案 1 :(得分:2)

您只需在@if内使用<option>条件并设置selected属性

<select class="form-control" name="displayNavigation" id="displayNavigation">
        <option value="1" @if($site['displayNavigation'] == 1) selected @endif>Yes</option>
        <option value="0" @if($site['displayNavigation'] == 0) selected @endif>No</option>
    @endif
</select>

答案 2 :(得分:2)

使用null coalescing operator ?? PHP 7 答案:

<select class="form-control" name="displayNavigation" id="displayNavigation">
    <option value="1" <?php echo ($site['displayNavigation'] ?? 2) == 1 ? 'selected' : ''; ?>>Yes</option>
    <option value="0" <?php echo ($site['displayNavigation'] ?? 2) == 0 ? 'selected' : ''; ?>>No</option>
</select>

如果您在PHP 7下,只需使用isset()做同样的事情:

<select class="form-control" name="displayNavigation" id="displayNavigation">
    <option value="1" <?php echo isset($site['displayNavigation']) && $site['displayNavigation'] == 1 ? 'selected' : ''; ?>>Yes</option>
    <option value="0" <?php echo isset($site['displayNavigation']) && $site['displayNavigation'] == 0 ? 'selected' : ''; ?>>No</option>
</select>

答案 3 :(得分:1)

您的if-else语句需要修改。这段代码将解决您的问题。

<select class="form-control" name="displayNavigation" id="displayNavigation">
    <option value="1" <?php if(isset($site['displayNavigation']) and $site['displayNavigation'] == 1){?>selected<?php } ?>>Yes</option>
    <option value="0" <?php if(isset($site['displayNavigation']) and $site['displayNavigation'] == 0){?>selected<?php } ?>>No</option>
</select>