我正在尝试制作餐馆菜单,我必须有类别和子类别,所以我创建了以下表格:
Table: Categories
ID
NAME
Table: Subcategories
ID
NAME
PRICE
DESCRIPTION
CATEGORIES_ID
我正在使用wanwizard的Codeigniter和DataMapper PHP。所以目前我有一些版本的2个foreach循环,但问题是,当我添加一个新的SUBCATEGORY并且只显示最后一个时,所以它没有列出该类别的所有子类别任何想法我在哪里我错了?
public function index()
{
$categories = new Category_model();
$subcategories = new Subcategory_model();
$categories->get();
$subcategories->get();
$recent_categories = array();
foreach ($categories as $category)
{
foreach($subcategories as $subcategory)
{
if($subcategory->categories_id == $category->id)
{
$single_category = array
(
'category_name' => $category->name,
'subcategory_name' => $subcategory->name,
'subcategory_description' => $subcategory->description,
'subcategory_price' => $subcategory->price,
);
}
}
array_push($recent_categories, $single_category);
}
$data = array
(
'categories' => $recent_categories,
);
$this->parser->parse('templates/content_menu', $data);
}
这就是观点:
{categories}
<div class="grid-12 ourmenu">
<!-- MENU TITLE -->
<h2>{category_name}</h2>
<hr/>
<!-- MENU ITEM -->
<h4>
<a class="clb-photo" href="<?php echo site_url('design/images/photos/food.jpg'); ?>">
{subcategory_name}
</a>
<span>{subcategory_price}</span>
</h4>
<p>{subcategory_description}</p>
</div>
{/categories}
答案 0 :(得分:2)
它在你的循环结构中。您需要在array_push
循环内foreach($subcategories as $subcategory)
进行操作。您的single_category
数组会在循环的每次迭代时被覆盖,但在覆盖之后才会将其添加到recent_categories
数组中。将您的代码更改为:
foreach ($categories as $category)
{
foreach($subcategories as $subcategory)
{
if($subcategory->categories_id == $category->id)
{
$single_category = array
(
'category_name' => $category->name,
'subcategory_name' => $subcategory->name,
'subcategory_description' => $subcategory->description,
'subcategory_price' => $subcategory->price,
);
array_push($recent_categories, $single_category); // ****** MOVED THIS LINE
}
}
}