CodeIgniter Forums
2 foreach loops - 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: 2 foreach loops (/showthread.php?tid=79381)



2 foreach loops - Lipe_Bogaci - 06-07-2021

Hello
How can i add 2 foreach loops in same table? One loop for users and another for user roles

<?php foreach($users as $row): ?>
 <tr>
  <td><?=$row['first_name']?></td>
  <td><?=$row['last_name']?></td>
  <td><?=$row['username']?></td>
  <td><?=$row['email']?></td>
  <td><?=$row['register_date']?></td>
  <td class="text-center"><?=$row['role_id']?></td>

</tr>
<?php endforeach?>


RE: 2 foreach loops - captain-sensible - 06-07-2021

if in a controller you assign data in the form $data = [ 'user'=>$usr,
'first_name'=>$first_name,
//then i dont see why you can't also add :
'userRole'=>$userRole]

in which case you only need one foreach loop in a view


but you can do things such as in view:
<html>
<table>

<?php
foreach($result as $res)
// $result is whats passed from controller and is an array, $res is a convient var to pass put
{
echo "<td>". $res["first_name"]. " ".$res["last_name"]. " </td> ";
}

foreach($result2 as $res2)

{
echo "<td>". $res2["someDbColumn"]." ".$res2["something_else"]."</td";

}
// the php code will just get processed in a linear manner
?>

</table>
</html>
SO you can have two foreach in a single table; however the main problem is going to be lining things up
or you have to use "dummy" <td> </td> to fill in the gaps containing perhaps &nbsp; which is none breaking space code


RE: 2 foreach loops - paliz - 06-07-2021

you want merg two associates arreay to gather

https://www.w3schools.com/php/func_array_merge.asp

Or join two table select columns you need