PHP嵌套foreach循环显示表格

标签 php mysql wordpress foreach

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

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

谢谢!

最佳答案

您走在正确的道路上。它会是这样的:

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

关于PHP嵌套foreach循环显示表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480939/

相关文章:

php - 当用户输入长文本而不添加空格时自动换行

html - wordpress 网站无法加载图像和 css

php - 从json文件添加到mysql db数据

PHP 没有将 MySQL 查询中的所有键写入数组

mysql - 创建 MySQL 查询时遇到问题

php - 准备似乎从字符串中删除引号,以便 mysql 日期时间字段不接受它

mysql - 有没有更快的方法来执行下面的 SQL 请求?

php - WooCommerce 购物车更改后更新短代码显示

css - 缩小尺寸时浏览器弄乱了侧边栏

php - PHP 中的 UPDATE 语句需要知道是否选择了新文件