I am trying to make a restaurant menu and I have to have Categories and Subcategories, so I created the following tables:
Table: Categories
ID
NAME
Table: Subcategories
ID
NAME
PRICE
DESCRIPTION
CATEGORIES_ID
I am using Codeigniter and DataMapper PHP by wanwizard. So currently I have some version of 2 foreach loops but the problem is that when I add a new SUBCATEGORY and only the last one appear, so it is NOT listing all the subcategories of the category Any ideas where I am wrong ?
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);
}
THIS IS THE VIEW:
{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}
It's in your structure of the loops. You need to do the array_push
INSIDE the foreach($subcategories as $subcategory)
loop. Your single_category
array is overwritten with each iteration of the loop, but it is never added to the recent_categories
array until after is has been overwritten. Change your code to:
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
}
}
}