dats
dats

Reputation: 123

nested foreach in codeigniter view

I have 4 tables: process, country, process_country and category. Each process belongs to a certain category. A country may have several processes available and a process may be available in several countries. Below is my database structure:

category table       process table        country table      process_country
--------------       --------------       -------------      ---------------
categoryid           processid            countryid          countryid
categoryname         processname          countryname        processid
                     categoryid
                     countryid

I have created functions to get all available processes for each country but I wanted to display the processes under their corresponding categories but i dont know how to implement. I am able to list all the processes and categories separately but I don't know how to nest them. I would like to achieve a page with a list like this for each country:

>  1. Category 1
>        Process 1
>        Process 2
>  2. Category 2
>        Process 3

I am thinking a nested foreach loop:

<?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 do not know how to implement another foreach loop for all processes under that 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); 

Upvotes: 3

Views: 7761

Answers (1)

Thamaraiselvam
Thamaraiselvam

Reputation: 7080

Inside $data['process'] you need to have category ID and Inside $data['category'] also

then only you can match both ,For example the foreach loop will be like following

<?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 matches then you will print them !

Happy coding !

Upvotes: 3

Related Questions