JasLamba
JasLamba

Reputation: 27

Using nested for loop to display data

I have login data that is stored in a MySQL database. From that data I was successfully able to group the logins every month organized by gender. For example, in January 1400 male users and 1500 female users logged in.

Now I'm struggling to display the data in a table.

Currently, I have it set up like this:

<div role="tabpanel" class="tab-pane fade active in" id="tab_content1" aria-labelledby="home-tab">
  <table id="datatable-fixed-header" class="table table-striped table-bordered">
    <thead>
      <tr>
        <th>Month</th>
        <th>Male Logins</th>
        <th>Female Logins</th>
      </tr>
    </thead>
    <tbody>
      <?php
        foreach ($maleLogin as $maleLog){
          $mthDateTime = DateTime::createFromFormat('n', $maleLog->month);
          foreach ($femaleLogin as $femaleLog) {
      ?>
      <tr>
        <td><?php echo $mthDateTime->format('F').' '.$maleLog->year; ?></td>
        <td><?php echo $maleLog->count;?></td>
        <td><?php echo $femaleLog->count;?></td>
      </tr>
      <?php } }?>
    </tbody>
  </table>
</div>

The problem is with my nested for loop. Currently, it displays the data like so.

Upvotes: 0

Views: 1140

Answers (3)

DFriend
DFriend

Reputation: 8964

I believe this will work for you. It utilizes the $key => $value form of foreach. $key is used to obtain the desired female count value.

This only works if your two datasets actually do have the exact same number records and are sorted exactly the same.

Note: I'm using Alternative syntax for control structures because it's a habit and because, IMO, it is easier to read when you're jumping in and out of the PHP processor. Likewise, I use <?= instead of <?php echo because it's a lot less typing.

<tbody>
    <?php
    foreach ($maleLogin as $key => $maleLog):
        $mthDateTime = DateTime::createFromFormat('n', $maleLog->month);
        ?>
        <tr>
            <td><?= $mthDateTime->format('F').' '.$maleLog->year; ?></td>
            <td><?= $maleLog->count; ?></td>
            <td><?= $femaleLogin[$key]->count; ?></td>
        </tr>
    <?php endforeach; ?>
</tbody>

Upvotes: 0

You are displaying every male login multiple times, for every female login that exists with the nested loops. Perhaps only use 1 foreach loop and display all info even if 0?

<?php
        foreach ($Login as $Log){
              if(maleLog)
                    do something for male login
              else
                    do something for female login
        }
?>

...something along those lines. The SQL statement above is probably your best choice though...

Upvotes: 1

Avi Teller
Avi Teller

Reputation: 299

the issue is foreach male you are looping through every female i would suggest some sort of sql query that joins the male and female based on date

SELECT * from male m LEFT join female f on m.date = f.date

something along those lines

Upvotes: 1

Related Questions