如何从 php 数组中 <select multiple="true"> 中的 select 选项?

How to select options inside <select multiple="true"> from php array?

mysql table 中的字段,未序列化时,returns 简单索引数组,如:

$biz_cats = array(4, 5, 8, 12, 17);

我使用所有类别填充 select 框:

SELECT `ID`, `cat_name` FROM `tbl_categories`

select 框的代码如下:

<select multiple="true" name="biz-cats[]" id="biz-cats" size="10">
    <option value="0">-- SELECT ONE --</option>

<?php
    // To populate all the categories to later-on allow user to select or de-select from
    if ($categories && is_array($categories)) {
        foreach ($categories as $category) {
            echo '<option value="' . $category['ID'] . '">' . $category['cat_name']</option>';
        }
    }
?>
</select>

由于此表格用于 Editing/Updating 记录(不是添加新记录),我需要根据 $biz_cats 进行一些选择 selected,我必须 select 恰好在表单的其他字段正在填充数据库中的值时。

你在找in_array

if(in_array($category['ID'], $biz_cats)){ $selected = 'selected'; } else { $selected = ''; }
echo '<option value="' . $category['ID'] . '" ' . $selected . '>' . $category['cat_name']</option>';