转换适合CI下拉列表的数组

时间:2011-07-05 13:22:49

标签: php arrays codeigniter

我正在使用CodeIgniter方法(db-> result_array())返回以下数组:

 Array
 (
[0] => Array
    (
        [id] => 5
        [lang_name] => ASM
    )

[1] => Array
    (
        [id] => 16
        [lang_name] => Bash
    )

[2] => Array
    (
        [id] => 17
        [lang_name] => Batch
    )

[3] => Array
    (
        [id] => 3
        [lang_name] => C
    )

[4] => Array
    (
        [id] => 11
        [lang_name] => C#
    )

[5] => Array
    (
        [id] => 4
        [lang_name] => C++
    )
 )

我需要一个具有这种格式的数组,将它传递给form_dropdown()CI函数:

 $atrLangDropDown = array(
    '1' => 'CPP',
    '2' => 'PHP',
    '3' => 'ASM'
);

我做过这样的事情:

public function getAllLangsSelect() {
    $this->db->select('*')->from($this->tableName)->order_by($this->tableName.'.lang_name');
    $q = $this->db->get();
    $data = array();
    array_push($data, '- Select Language -');

    foreach ($q->result_array() as $row) {  
        array_push($data, $row['lang_name']);
    }

    return $data;

}

但它必须保存存储在DataBase中的原始ID,因此它不能正常工作。

欢迎任何提示或帮助。这是我第一次做这种操作。

1 个答案:

答案 0 :(得分:1)

试试这个:

public function getAllLangsSelect()
{
    $query = $this->db
        ->order_by('lang_name')
        ->get($this->tableName);

    $options[''] = '- Select Language -';

    foreach ($query->result() as $row)
    {  
        $options[$row->id] = $row->lang_name;
    }

    return $options;
}