Codeigniter从数据库创建关联数组并在下拉列表中使用

时间:2012-06-22 23:56:59

标签: php arrays forms 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;      
    }

查看:

//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

代码提供了一个多维数组

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...

如何使用关联数组替换上面的结果,其中ID键是类别ID并且值是类别标题?

示例:

$categories = array(
    "23" => "some title",
    "14" => "another title",
);

4 个答案:

答案 0 :(得分:5)

解决方案示例:

$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
        )

)
*/

答案 1 :(得分:1)

做类似的事情:

foreach($categories as $category){
    $category_array[$category['cat_id']] = $category['cat_title'];
}

$categories = $category_array;

这会将类别ID指定为数组键,将标题指定为值,以便在下拉列表中使用。

答案 2 :(得分:0)

您可以在html_helper中使用_list()函数从多维数组中创建嵌套列表

答案 3 :(得分:0)

使用这个简单的方法,

$query = $this->db->get_where('table', array('table_id' => $id));

        $queryArr = $query->result();        

        foreach ($queryArr[0] as $key=>$val)
        {
            $row[$key]=$val;
        }

print_r($row); //this will give associative array