Home > Back-end >  How to have a nested foreach loop without having duplicate child records
How to have a nested foreach loop without having duplicate child records

Time:12-06

I'm a beginner and new to Codeigniter3. I've made a checklist system which has two radio buttons, Fine and Not fine. A person will check if all the options are fine or not. If there is an issue in any option he will select not fine. Then on the "Issues" page I'm only showing the options he selected "Not fine". He will be able to add multiple comments on each Issue. I've done all this part. The only problem I'm facing is how to show the comments under every option? What's happing now is for eg. I have 3 issues and each issue has 1 comment but will still show all the comments under each and every option. I know this is the normal behavior of nested loop but I don't know how to show the comments under their own respective issues.

<?php foreach($issues as $i=>$issue) : ?>

   <div >
        <!-- Radio Group -->
        <div >     
             <h6><?php echo $issue['checks']; ?></h6>
        </div>
                                            
        <div >
             <?php foreach($comments as $comment) : ?>
                 <label >
                   <input type="hidden" name="chk_value[<?php echo $i; ?>]" value="<?php echo $issue['checks']; ?>">
                   <input type="text" name="comment[<?php echo $i; ?>]" value="<?php echo $comment['comment']; ?>" >
                 </label>
             <?php endforeach; ?>
       </div>
                                            
   </div>

   <div ></div>

<?php endforeach; ?>

CodePudding user response:

The problem seems to be a lack of relation between issues and comments. I'm not sure what your data structure is, but you should either make it nested, and then use it like this

foreach($issues as $issue){
  foreach($issue['comments'] as $comment){
    //show comment
  }
}
    

or have some kind of 'id' that could link them

foreach($issues as $issue){
  foreach($comments as $comment){
    if($comment['issue_id'] == $issue['id']){
      //show comment
    }
  }
}
  • Related