Cyb*_*kie 0 php forms arrays codeigniter
我有一个名为的数据库表Categories.我想创建一个包含db中所有类别的表单下拉列表.我的解决方案是创建一个关联数组并将其添加到form_dropdown()函数的第二个参数中.我的结果是一个不需要的多维数组.
模型:
function list_categories()
{
$user_id = $this->tank_auth->get_user_id();
$this->db->where('user_id', $user_id);
$this->db->order_by("date_created", "desc");
$query = $this->db->get('categories');
return $query;
}
Run Code Online (Sandbox Code Playgroud)
视图:
//create array
$categories = array();
if ($query->num_rows() > 0)
{
$categories = $query->result_array();
}
//create dropdown
echo form_dropdown('category', $categories, $date_created); //selected value based date created
Run Code Online (Sandbox Code Playgroud)
代码给出了一个多维数组
Array (
[0] => Array ( [cat_id] => 27 [user_id] => 3 [cat_title] => Some Title [status] => 0 [date_created] => 2012-06-22 18:48:14 )
[1] => Array ( [cat_id] => 24 [user_id] => 3 [cat_title] => Title [status] => 0 [date_created] => 2012-06-20 19:37:47 )
[2] => Array ( [cat_id] => 23 [user_id] => 3 [cat_title] => Another Title [status] => 0 [date_created] => 2012-06-20 18:25:45 )
etc...
Run Code Online (Sandbox Code Playgroud)
如何用关联数组替换上面的结果,其中ID键是类别ID并且值为类别标题?
例:
$categories = array(
"23" => "some title",
"14" => "another title",
);
Run Code Online (Sandbox Code Playgroud)
解决方案的例子:
$categories=array(
'0'=>array("cat_id"=>"27","cat_title"=>"some title"),
'1'=>array("cat_id"=>"24","cat_title"=>"Title"),
'2'=>array("cat_id"=>"23","cat_title"=>"Another Title"),
);
foreach($categories as $catID=>$categoriesData){
$finalArray[$categoriesData["cat_id"]]=$categoriesData;
}
print_r($finalArray);
/*
OUTPUT
Array
(
[27] => Array
(
[cat_id] => 27
[cat_title] => some title
)
[24] => Array
(
[cat_id] => 24
[cat_title] => Title
)
[23] => Array
(
[cat_id] => 23
[cat_title] => Another Title
)
)
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9303 次 |
| 最近记录: |