Search code examples
phpcodeigniter-4

Loop data from 2 different model php codeigniter 4


I have table to display data from 2 of my model

<tbody>
    <?php $numbering = 1;
     foreach ($data1 as $row) :
         foreach ($data2 as $rowData) : ?>
           <tr>
               <td><?= $numbering++; ?></td>
               <td><?= $row["id"]; ?></td>
               <td><?= $row["name"]; ?></td>
               <td><?= $rowData["question"]; ?></td>
               <td><?= $rowData["indicator 1"]; ?></td>
               <td><?= $rowData["indicator 2"]; ?></td>
               <td><?= $rowData["indicator 3"]; ?></td>
               <td><?= $rowData["indicator 4"]; ?></td>
               <td><?= $rowData["indicator 5"]; ?></td>
            </tr>
          <?php endforeach;
          endforeach; ?>
  </tbody>

data 1 and data 2 from my controller

public function index()
{
    $display1 = $this->model1->findAll();
    $display2 = $this->model2->findAll();
    $data = [
        'title' => 'Page Title',
        'data1' => $display1 ,
        'data2' => $display2 ,
        'content'    => 'Backend/viewDisplay'
    ];

    return view('layouts/v_wrapper', $data);
}

displayed like this enter image description here

How to display it so question 1 doesn't repeat on user 1 and question 2 doesn't repeat on user 1 and so on. In total it should only have 4 column.

  • User 1
    • Question 1
    • Question 2
  • User 2
    • Question 1
    • Question 2

Solution

  • I Solve it

    my view

    <tbody>
        <?php $numbering = 1;
         foreach ($data1 as $key => $value) : ?>
            <tr>
               <td><?= $key + 1 ?></td>
               <td><?= $value->id?></td>
               <td><?= $value->name?></td>
               <td><?= $value->question?></td>
               <td><?= $value->indicator 1?></td>
               <td><?= $value->indicator 2?></td>
               <td><?= $value->indicator 3?></td>
               <td><?= $value->indicator 4?></td>
               <td><?= $value->indicator 5?></td>
             </tr>
         <?php endforeach; ?>
     </tbody>
    

    my model (join function)

    function getAll()
    {
        $builder = $this->db->table('table2');
        $builder->select('*');
        $builder->join('table1', 'table1.id = table2.id');
        $builder->orderBy('name', 'ASC');
        $query = $builder->get();
    
        return $query->getResult();
    }
    

    my controller

    public function index()
    {
        $display2= $this->model2->getAll();
        $data = [
            'title' => 'Page Title',
            'data2' => $display2,
            'content'    => 'Backend/viewDisplay'
        ];
    
        return view('layouts/v_wrapper', $data);
    }
    

    i change findAll() to getAll()

    thanks to Guido Faecke in comment