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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题