phparraysloopscodeignitermodel-view-controller

How to print multiple HTML tables from dynamic data in a CodeIgniter application?


I have two tables meals type and meals. I want to print each meals corresponding to its meals type.

Error is that only showing last meals type meals only.

view page is like

View

<?php
foreach ($mealstype as $type) {
    ?>  
    <h2><?php echo $type->type; ?></h2>
    <table class="table table-bordered">
        <tr>
            <th>Meals</th>
            <th>Price</th>

        </tr>
    </thead>
    <tbody>
        <?php
        foreach ($meals as $meals_get) {
            ?>
            <tr>
                <td><?php echo $meals_get->item; ?></td>
                <td><?php echo $meals_get->price; ?></td>

            </tr>
        <?php } ?>
        <tr>
            <td> <input type="checkbox" class="ck" value="total">  Toal</td>
            <td>2050</td>

        </tr>
    </tbody>
    </table>
    <?php
}
?>

Controller

function availability() {

    $this->data['mealstype'] = $this->Home_model->mealstype();
    foreach ($this->data['mealstype'] as $type) {
        $typeid = $type->id;
        $meals[] = $this->Home_model->meals($typeid, $hotel_id);
    }
    $this->data['meals'] = $meals[];
    $this->load->view('home2', $this->data);
}

Solution

  • Please check this answer

    Controller:

    public function availability() {  
        $build_array = array();
        mealstype= $this->Home_model->mealstype();
        foreach($mealstype as $row){
            $build_array[] = array(
            'parent_array' => $row,
            'child_array' =>$this->Home_model->meals($row->id,$hotel_id),
            'child_sum'     =>$this->Home_model->meals_sum($row->id,$hotel_id)
            );
        }
        $this->data['build_array'] = $build_array;
    }
    

    and the view page is like this:

    View:

    <?php foreach($build_array as $type){?> 
    <h2><?php echo $type['parent_array']->type;?></h2>
    <table class="table table-bordered">
        <tr>
            <th>Meals</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
    <?php
    foreach ($type["child_array"] as $meals_get) {?>
        <tr>
            <td><?php echo $meals_get->item;?></td>
            <td><?php echo $meals_get->price;?></td>
        </tr>
    <?php }?>
        <tr>
            <td>  Toal</td>
            <td>2050</td>
        </tr>
    <?php } ?>