Codeigniter:类别和子类别

时间:2014-07-24 02:17:50

标签: php mysql arrays codeigniter codeigniter-datamapper

我正在尝试为餐馆菜单制作类别子类别

子类别还有其他字段,例如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

有人可以指点我如何让它发挥作用吗?感谢。

2 个答案:

答案 0 :(得分: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"
}

答案 1 :(得分: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;
    }
}

Out out of that

阵列( 'Categories'=>阵列(小类) )