2012-06-22 59 views
0

我有一個名爲Categories的數據庫表。我想創建一個包含數據庫中所有類別的表單下拉菜單。我的解決方案是創建一個關聯數組並將其添加到form_dropdown()函數的第二個參數中。我的結果是一個不需要的多維數組。Codeigniter從數據庫創建關聯數組並在下拉菜單中使用

型號:

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

我怎麼能代替上面的Associativ結果e數組,其中ID鍵是類別標識並且值類別標題?

實施例:

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

回答

5

用一個例子SOLUTION:

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

) 
*/ 
+0

謝謝!這很好地工作 – CyberJunkie

1

做類似:

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

$categories = $category_array; 

這將分配的類別ID作爲數組的鍵,和標題作爲值,在下拉使用。

+0

感謝你的工作代碼! – CyberJunkie

0

您可以使用_list()函數在html_helper使從多維數組

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 
相關問題