1
// 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 的选项值 =“selected”,但在我上面的代码中,它只选择 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>';
    }

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

4

1 回答 1

3

你比较$list->id第一个 $series_item_id: $series_item_id [0] ->series_id

您需要将其他foreach放入现有的:

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>';

}
于 2012-05-31T20:44:56.993 回答