Pat
Pat

Reputation: 1203

PHP nested foreach loops to display table

I'm looking to generate an HTML table like below.

|nick_name| bookmarked_sites  |
-------------------------------
| admin   | http://test1.com  |
|         | http://test2.com  |
|         | http://test3.com  |
-------------------------------
| John    | http://mysite.com |
-------------------------------

I'm query the database using $wpdb and it's building an array of information which looks like this:

$userquery = $wpdb->get_results("SELECT * FROM bookmarks");
print_r($userquery);

Array ( 
[0] => stdClass Object ( 
    [id] => 1 [user_id] => 1 [post_id] => 1654,1532,1672,1610,1676 ) 
[1] => stdClass Object ( 
    [id] => 3 [user_id] => 6 [post_id] => 1680,1654 ) )

I started to build my first foreach to extract the user_id, then I had a nested foreach to extract the post_id for that user. But I'm realizing now that I can't easily build an HTML table off that concept.

I'm having a hard time conceptualizing the logic to put this all together.

Thanks!

Upvotes: 0

Views: 2381

Answers (2)

Svetoslav
Svetoslav

Reputation: 4686

This is possible way to make your table.. With the data you have from your query..

<table>
  <thead>
    <tr>
      <th>user_id<th>
      <th>post_id<th>
    </tr>
  </thead>
  <tbody>
    <?php foreach($userquery as $uq): ?>
    <tr>
      <td><?php echo $uq['user_id']; ?></td>
      <td>
        <?php
           $posts = explode(',', $uq['post_id']);
           if(count($posts)>0):
           ?>
           <table>
             <?php foreach($posts as $p): ?>
             <tr><td><?php echo $p; ?> </td></tr>
             <?php endforeach; ?>
           </table>
     <?php else: ?>
           No posts...
     <?php endif; ?>
      </td>
    </tr>      
    <?php endforeach; ?>
  </tbody>
</table>

Upvotes: 1

Hugo Delsing
Hugo Delsing

Reputation: 14173

You are on the right track. It would something like:

echo '<table>';
foreach ($userquery as $user) {
  //load sites into $loadedsites

  $rowheight = count($loadedsites);
  $c = 0;

  //if there is a user without any sites, the rowheight would be 0.
  //You need to deceide what to do than, because now it wouldnt show the user at all.

  foreach($loadedsites as $site) {

    if ($c==0)
      echo '<tr><td rowspan="'.$rowheight.'">'.$user->user_id.'</td><td>'.$site->url.'</td></tr>';
    else
      echo '<tr><td>'.$site->url.'</td></tr>';

    $c++;
  }
}
echo '</table>';

Upvotes: 1

Related Questions