2014-07-24 188 views
0

我想使類別子類別爲餐館的菜單。Codeigniter:類別和子類別

子類別有像pricedescription類別附加字段僅具有idname。所以我決定和這兩張桌子一起去。

Categories -> ID, NAME 
Subcategoires -> ID, NAME, DESCRIPTION, PRICE, CATEGORIES_ID, 

現在我正在嘗試構造它們來製作一個漂亮的菜單。

我也在使用DataMapper for Codeigniter。

到目前爲止,我有這樣的:

$categories = new Category_model(); 
$subcategories = new Subcategory_model(); 
$categories->get(); 
$subcategories->get(); 

$recent_categories = array(); 
$recent_subcategories = array(); 

foreach ($categories as $category) 
{ 
    $single_category = array 
    (
     'category_id' => $category->id, 
     'category_name' => $category->name, 
    ); 

    foreach ($subcategories as $subcategory) 
    { 
     if ($subcategory->categories_id == $category->id) 
     { 
      $single_subcategory = array 
      (
       'subcategory_id' => $subcategory->id, 
       'subcategory_name' => $subcategory->name, 
       'subcategory_description' => $subcategory->description, 
       'subcategory_price' => $subcategory->price, 
      ); 
     } 
    } 

    array_push($recent_categories, $single_category); 
    array_push($recent_subcategories, $single_subcategory); 
} 

這幾乎是一個小問題工作正在打印既SUBCATEGORIES兩個CATEGORIES。哪裏需要每個只有一個。

所以現在正在尋找這樣的:

ALCOHOL 
    - VODKA 
    - COLA 
NON-ALCOHOL 
    - VODKA 
    - COLA 

,顯然我希望它是VODKAALCOHOLCOLANON-ALCOHOL

有人可以請我指出如何使其工作?謝謝。

回答

0

也許你應該立即填充數組。

假設您的內容是這樣的..

$categories = array("alcohol", "non-alcohol"); 
    $subcategories = array(
        (object)array("category" => "alcohol", "name" => "vodka"), 
        (object)array("category" => "non-alcohol", "name" => "cola") 
        ); 

    foreach ($categories as $category) 
    { 
     $recent_categories[] = $category; 

     foreach ($subcategories as $subcategory => $subcat) 
     {    
      $recent_subcategories[$subcat->name][] = $subcat->name; 
     } 
    } 

這將導致:

array(2) { 
    [0]=> 
    string(7) "alcohol" 
    [1]=> 
    string(11) "non-alcohol" 
} 

array(2) { 
    ["alcohol"]=> 
    string(5) "vodka" 
    ["non-alcohol"]=> 
    string(4) "cola" 
} 
+0

這將覆蓋同一類別的最後一個產品名稱,如果該類別有多個產品 –

+0

是的,我看到但我希望信息在數據庫中,而不是硬編碼 – Unsparing

0
$categories = array("alcohol", "non-alcohol"); 
$subcategories = array(
       (object)array("category" => "alcohol", "name" => "vodka"), 
       (object)array("category" => "non-alcohol", "name" => "cola") 
       ); 
$recent_subcategories = array(); 
foreach ($categories as $category) 
{ 
    $recent_categories[] = $category; 

    foreach ($subcategories as $subcategory => $subcat) 
    {    
     $recent_subcategories[$subcat->name][] = $subcat->name; 
    } 
} 

失放的是

陣列( '分類'= > array(Subcategories) )