0

我正在寻找生成如下所示的 HTML 表格。

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

我正在使用 $wpdb 查询数据库,它正在构建一个信息数组,如下所示:

$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 ) )

我开始构建我的第一个foreach以提取 . user_id,然后我有一个嵌套来为该用户foreach提取. post_id但我现在意识到我不能轻易地根据这个概念构建一个 HTML 表格。

我很难概念化将所有这些放在一起的逻辑。

谢谢!

4

2 回答 2

1

你在正确的轨道上。它会是这样的:

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>';
于 2013-03-18T15:57:16.070 回答
1

这是制作表格的可能方法..使用您从查询中获得的数据..

<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>
于 2013-03-18T15:57:24.160 回答