Nested foreach in codeigniter view
I have 4 tables: process, country, process_country and category. Each process belongs to a specific category. A country can have multiple processes available, and a process can be available in multiple countries. Below is the structure of my database:
category table process table country table process_country
-------------- -------------- ------------- ---------------
categoryid processid countryid countryid
categoryname processname countryname processid
categoryid
countryid
I created functions to get all the available processes for each country, but I wanted to display the processes under their respective categories, but I don't know how to implement them. I can list all processes and categories separately, but I don't know how to nest them. I would like to get a page with a listing like this for each country:
> 1. Category 1
> Process 1
> Process 2
> 2. Category 2
> Process 3
I think the nested foreach loop is:
<?php
foreach ($category as $c) {
echo "<li>" . $c->CategoryName . "</li>";
foreach ($process as $r) {
echo "<li><a href=\"" . base_url() . "index.php/process/id/" . $r->ProcessID . "\" target=\"_blank\">" . $r->ProcessName . "</a></li>";
}
}
?>
but I don't know how to implement a different foreach loop for all processes in this category.
Controller:
$data['process'] = $this->getProcesses(); //function that gets process available for the country
$data['category'] = $this->getCategories(); //function that gets all categories
$this->load->view('includes/template', $data);
source to share
Inside $data['process']
you need to have category ID
Inside $data['category']
as well
then you can only match both. For example, the loop foreach
would look like this
<?php
foreach ($category as $c) {
echo "<li>" . $c->CategoryName . "</li>";
foreach ($process as $r) {
if($r['cat_id']==$c['id']){
echo "<li><a href=\"" . base_url() . "index.php/process/id/" . $r->ProcessID . "\" target=\"_blank\">" . $r->ProcessName . "</a></li>";
}
}
}
?>
if both Id
match, then you will print them!
Happy coding!
source to share