【问题标题】:PHP nested foreach loops to display tablePHP嵌套foreach循环以显示表格
【发布时间】:2013-03-07 00:46:37
【问题描述】:

我希望生成一个如下所示的 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 表格。

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

谢谢!

【问题讨论】:

  • 使用每个数组的count 知道rowspan 使用什么。
  • 您的具体问题是什么?
  • 对不起,我不清楚。我的确切问题是:1)我使用嵌套的 foreach 是否走在正确的道路上,以及 2)我将如何使用嵌套的 foreach 构建上面的 HTML 表?

标签: php mysql wordpress foreach


【解决方案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>';

【讨论】:

  • 您的回答几乎奏效了。它正确地显示了带有行高的用户名列,但它只为所有用户显示 1 个书签,并且一直重复直到完成。我不确定它为什么会这样做。
  • 获取网站的查询是什么?检查源时的行高是多少?
  • 我的错误。我在我身边发现了一个错字。今天看这个太久了。这是工作。谢谢!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 2012-09-17
    • 2018-05-21
    • 2013-07-05
    • 1970-01-01
    相关资源
    最近更新 更多