I have a few different sets of data that go through a foreach loop. A lot of the code inside each foreach loop is similar, almost identical, but I'm using variables based on previously defined arrays as well as on that initial data put into the foreach loop. Is there a way to combine these loops into some sort of function without having to pass all of that data into the function?
Meaning, can I define a function within a loop and have it use that data in some way? I need to do this because if I want to display only those rows that have associated data, I loop through using the data. But if I want to display all rows whether there is associated data for it or not, then I need to use a different array to loop through.
I need to do two separate loops for the else
because it needs to get layout items common to all arrangements and layout items specific to this arrangement, and then if there's data I need to display it one way, and if it's empty, I need to do something different, so I have to check for that as well.
Here's an example of the multiple loops using the same data:
if($hideempty == 'hide'){
foreach($bannerArray as $bannerID => $records){
foreach($records as $id => $record){ ?>
<tr>
<td><?php echo $record['layout_name']; ?></td>
<td><?php echo $record['company_name']; ?></td>
</tr>
<?php }
}
} else {
$layoutGroupArray = mysqli_fetch_assoc(mysqli_query($link, "SELECT `set_layout_group` FROM `SetTopics` WHERE `set_id` = $setID"));
$layoutGroup = $layoutGroupArray['set_layout_group'];
foreach($banners[0] as $bannerID => $layoutInfo){
if(isset($bannerArray[$bannerID])){
foreach($bannerArray[$bannerID] as $id => $record){ ?>
<tr>
<td><?php echo $record['layout_name']; ?></td>
<td><?php echo $record['company_name']; ?></td>
</tr>
<?php }
} else { ?>
<tr>
<td><?php echo $layoutInfo['layout_name']; ?></td>
<td>empty</td>
</tr>
<?php }
}
foreach($banners[$layoutGroup] as $bannerID => $layoutInfo){
if(isset($bannerArray[$bannerID])){
foreach($bannerArray[$bannerID] as $id => $record){ ?>
<tr>
<td><?php echo $record['layout_name']; ?></td>
<td><?php echo $record['company_name']; ?></td>
</tr>
<?php }
} else { ?>
<tr>
<td><?php echo $layoutInfo['layout_name']; ?></td>
<td>empty</td>
</tr>
<?php }
}
}
It doesn't have to be a function that I use, but I'm not sure how to write this code efficiently. I am doing a lot of repeating, but I can't come up with another way to access the data I need without doing this repeating.