简体   繁体   English

处理多选结果数组-CodeIgniter

[英]Manipulating Results Array for Multiselect—CodeIgniter

I'm trying to populate a multiselect in my view with the results from a query to the database. 我试图用查询到数据库的结果填充视图中的多选。 Sorry if this is a very basic question—I'm a bit new to CodeIgniter and MVC. 抱歉,如果这是一个非常基本的问题,我对CodeIgniter和MVC还是陌生的。

My model simply gets all records from a table: 我的模型只是从表中获取所有记录:

function getAll() {
            $query = $this->db->get('example');
            return $query->result_array();
    }

I then hope to pass the results to my view to populate a multiselect form element. 然后,我希望将结果传递给我的视图,以填充多选表单元素。 However, the associative array that is returned does not provide the results I'd like. 但是,返回的关联数组不提供我想要的结果。

What I get: 我得到的是:

    [0] Array
        (
            [id] => 6
            [name] => Bob    

What I'd like to get: 我想要得到什么:

[0] Array
    (
        [6] => Bob
        [7] => Linda

Am I missing something with my query that would achieve my desired results? 我的查询中缺少某些可以达到预期结果的东西吗? Should I just use a foreach to create a new array that will be formatted the way I would like? 我应该只使用一个foreach来创建一个新的数组,该数组将按照我想要的方式进行格式化吗? If so would this foreach belong in my controller or view. 如果是这样,则此foreach属于我的控制器或视图。

Thank you for your help. 谢谢您的帮助。

Try this: 尝试这个:

function getAll()
{
    $items = $this->db->get('example')->result_array();
    if(empty($items))
        return array();

    $res = array();
    $i   = 0; 
    while($i < count($items))
    {
        $res[$items[$i]['id']] = $items[$i]['name'];
        ++$i;
    }

    return array($res);
}

The most efficient way would be to use active record, because it just gets the data from the column 'name' in your table) 最有效的方法是使用活动记录,因为它只是从表中的“名称”列获取数据)

$this->db->select('name')
         ->from('example');

return $this->db->get()->result();

If you were going to use a foreach loop, if you process the results in the controller you would have to process them again in the view, so you may as well send the entire result array to the view and process them in the view. 如果要使用foreach循环,则如果在控制器中处理结果,则必须在视图中再次对其进行处理,因此也可以将整个结果数组发送到视图并在视图中进行处理。 This is useful if you need to use most of the columns of one particular table in your view. 如果您需要使用视图中一个特定表的大多数列,这将很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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