CodeIgniter Forums
two foreach connect - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: two foreach connect (/showthread.php?tid=77807)



two foreach connect - Germanikus - 10-20-2020

Hello everyone,
I have a question.
In my website I often have to link two different "foreach".
I usually do it like this

PHP Code:
foreach ($view_category_main as $main):
    
$SQL "SELECT * FROM db_todo_mission WHERE db_todo_mission.tb_todo_mission_main = ".$main['category_id']." GROUP BY db_todo_mission.tb_todo_mission_sub";
    
$query $this->db->query($SQL);
    foreach (
$query->result() as $sub):
        echo 
$sub->tb_todo_mission_sub;
    endforeach;
endforeach; 


Now i wonder if there is a more elegant way to store it in modal and then have it retrieved?


RE: two foreach connect - includebeer - 10-22-2020

If you follow the model-view-controller pattern, the database query should be in a model and the output should in a view.

You could do something like this:

MODEL
PHP Code:
// Add & in front of $main
foreach ($view_category_main as &$main)
{
    $SQL "SELECT * FROM db_todo_mission WHERE db_todo_mission.tb_todo_mission_main = ".$main['category_id']." GROUP BY db_todo_mission.tb_todo_mission_sub";
    $query $this->db->query($SQL);
    // Store the results for each category
    $main['sub'] = $query->result()



VIEW
PHP Code:
foreach ($view_category_main as $main):
    // Loop on the sub array for each category
    foreach ($main['sub'] as $sub):
        echo $sub->tb_todo_mission_sub;
    endforeach;
endforeach;