• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
two foreach connect

#1
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?
Reply

#2
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; 
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.