php 获取codeigniter中的列值数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19360859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get array of column values in codeigniter
提问by Majed DH
i have a table with this structure:
我有一个具有这种结构的表:
ID int(11)
ID 整数(11)
user_id int(11)
user_id int(11)
notification_event_id int(11)
notification_event_id int(11)
how can i get an array that contains all values of user_id column :
我怎样才能得到一个包含 user_id 列的所有值的数组:
EX:
前任:
Array([0]=> 1,[1]=>2,[2]=>3,[3]=>4,[4]=>5,[5]=>6);
and without looping on the result_array()
value and moving the user_ids to a new integers array
并且不循环result_array()
值并将 user_ids 移动到新的整数数组
is that possible?
那可能吗?
回答by TKC
Each results row is itself an array so somelooping is necessary! Why would you need to do it differently?
每个结果行本身就是一个数组,因此需要进行一些循环!为什么你需要以不同的方式做呢?
The most straightforward way to do what you want is:
做你想做的最直接的方法是:
// Model
function get_all_userid()
{
$query = $this->db->get('table_name');
$array = array();
foreach($query->result() as $row)
{
$array[] = $row['user_id']; // add each user id to the array
}
return $array;
}
// Controller
function user_list()
{
$data = $this->your_model->get_all_userid(); // get results array from model
$this->load->view('your_view', $data); // pass array to view
}
Obviously you'll need to adjust the table/model names to match the ones you're using.
显然,您需要调整表/模型名称以匹配您正在使用的名称。
回答by Patrick Maciel
I did a research and found this:
我做了一个研究,发现了这个:
Note: a 'magic' solution for that, for example: using a codeigniter custom function, I think doesn't exist in actual framework version. So, you need create a function in Model or in a Custom Helper.
注意:对此的“神奇”解决方案,例如:使用 codeigniter 自定义函数,我认为在实际框架版本中不存在。因此,您需要在 Model 或 Custom Helper 中创建一个函数。
Reference:Populate drop down list from database
参考:从数据库填充下拉列表
Using your Model
使用你的模型
// Controller
$data['city_list'] = $this->City_model->get_dropdown_list();
$this->load->view('my_view_file', $data);
Model:
// Model (or create a helper -- see below)
function get_dropdown_list()
{
$this->db->from('city');
$this->db->order_by('name');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[$row['id']] = $row['name'];
}
}
return $return;
}
// View
<?php echo form_dropdown('city_id', $city_list, set_value('city_id', $city_id));
Using a Helper
使用助手
if ( ! function_exists('drop_down'))
{
function drop_down($name, $match, $data)
{
$form = '<select name="'.$name.'"> ' ."\n";
foreach($data as $key => $value)
{
$selected = ($match == $key) ? 'selected="selected"' : NULL ;
$form .= '<option value="'. $key .'" '. $selected .'>'.$value.'' . "\n";
}
$form .= '</select>' . "\n";
return $form;
}
}
In the view
echo drop_down('mylist', 3, $data);