简体   繁体   中英

Codeigniter: result_array() to form_multiselect()

I am pulling a queried result_array() and placing that array as the fields to select from in a form_multiselect(). What I can't seem to figure out is why the multi-select shows the array indexes followed by each queried result. Is this a problem with my array or are there form_multiselect options I am missing for the array indexes to not be shown?

And my code below:

public function get_tags() {
    $this->db->select('tag_name');
    $this->db->distinct();
    $this->db->from('offers_tags');

    $query = $this->db->get();

    $tags = $query->result_array();

    return $tags;  
}

My controller:

$this->data['tags']=$this->offer_model->get_tags();

My view:

<div class="control-group">
            <?= form_label('Tags: ', 'tag_targets', $label_attr);?>

            <div class="controls">
                <?= form_multiselect('tag_targets[]',$tags,'','id="geo-select"');?>
            </div>
</div>

Maybe You have the order of the parameters wrong.

The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value or values you wish to be selected http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html

You could also var_dump the array to check the values if you're not sure

I do not think you are specifying the options correctly. http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html

you should be specifying the options like this:

$tags = array(
    'tag1Value'  => 'tag1Name',
    'tag2Value'  => 'tag2Name',
    'tag3Value'  => 'tag3Name',
    'tag4Value'  => 'tag4Name'
);

However what you are returning from your get_tags function is:

array(
    0 => array('tag_name'=> 'Tag1'),
    1 => array('tag_name'=> 'Tag2'),
    2 => array('tag_name'=> 'Tag3')
)

Each result is a separate array contained with a wrapping array.

You can get the results into the format needed for form_multiselect by looping through the items and creating a new array. In your get_tags function you can do the following.

$tags = array();
foreach ($query->result_array() as $row)
{
   $tags[$row['tag_name']] = $row['tag_name'];
}
return $tags;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM