dongshen7407 2013-03-18 15:44
浏览 72
已采纳

PHP嵌套的foreach循环显示表

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!

  • 写回答

2条回答 默认 最新

  • douxi4114 2013-03-18 15:57
    关注

    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>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal