在多选下拉列表中设置多个默认选定值

时间:2012-05-31 20:18:35

标签: php mysql arrays codeigniter select

// Get Series List
    $this->load->model('Series_model');
    $serieslist = $this->Series_model->gettypelist($userid, 'e');

    $series_item_id = 0;

    $this->db->select('series_id');
    $this->db->where('type_id', 13);
    $this->db->where('series_type', 'e');
    $series_item_query = $this->db->get('series_items');

    if ($series_item_query->num_rows() > 0) {
        $series_item_id = $series_item_query->result();
    }
    //print_r($series_item_id);

    $data['serieslist'] = '<select name="series_id[]" class="type input_select" multiple="multiple">';
    $data['serieslist'] .= '<option value="">None</option>';
    foreach ($serieslist as $list) {
        $data['serieslist'] .= '<option value="' . $list->id . '" ' . ($series_item_id[0]->series_id === $list->id ? 'selected="selected"' : '') . '>' . $list->title . '</option>';
    }
    $data['serieslist'] .= '</select>';

以上是我正在使用的代码。我希望能够为选择下拉菜单的多个值设置多个selected =“selected”。例如:

<select name="series_id[]" class="type input_select" multiple="multiple">
    <option value="">None</option>
    <option value="4">Event Series: Test 1</option>
    <option value="5">Event Series: Test 2</option>
    <option value="16">Event Series: Test 3</option>
    <option value="17">Event Series: Test 4</option>
    <option value="18">Event Series: Test 5</option>
    <option value="19">Event Series: Test 6</option>
    <option value="20">Event Series: Test 7</option>
    <option value="21">Event Series: Test 8</option>
</select>

我希望选择4 16和19的选项值=“已选择”,但在上面的代码中,它只选择4然后停止。我错过了什么?如果您需要进一步的信息,请告诉我。

提前致谢。

编辑:

print_r的结果:

Array ( [0] => stdClass Object ( [series_id] => 4 ) [1] => stdClass Object ( [series_id] => 16 ) [2] => stdClass Object ( [series_id] => 19 ) )

更新的代码:

foreach ($serieslist as $list) {
        $data['serieslist'] .= '<option value="' . $list->id . '" ' . (in_array($list->id, $series_item_id, TRUE) ? 'selected="selected"' : '') . '>' . $list->title . '</option>';
    }

以上更新的代码不起作用。

1 个答案:

答案 0 :(得分:3)

您将$list->id与第一个$ series_item_id进行比较:$ series_item_id [0] - &gt; series_id

您需要将其他foreach放入现有的:{/ p>

foreach ($serieslist as $list) {
    foreach ($series_item_id as $series_item) {
         $data['serieslist'] .= '<option value="' . $list->id . '" ' . ($series_item->series_id === $list->id ? 'selected="selected"' : '') . '>' . $list->title . '</option>';
    }
}

或将series_id作为数组获取并使用in_array()

$series_array = array();

foreach ($series_item_id as $series_item) {
     $series_array[] = $series_item->series_id;
}

foreach ($serieslist as $list) {

         $data['serieslist'] .= '<option value="' . $list->id . '" ' . (in_array($series_array, $list->id) ? 'selected="selected"' : '') . '>' . $list->title . '</option>';

}