doukan4039 2014-10-19 19:58
浏览 44
已采纳

在MySQL内部的id迭代更改中打印新的<div>,同时从MySQL结果循环

I have this MySQL table:

+------------+-------------+
| contact_id | _company_id |
+------------+-------------+
|          1 |           1 |
|          2 |           1 |
|          3 |           1 |
|          4 |           2 |
|          5 |           2 |
+------------+-------------+

Im trying to print a new <div> containing all rows with the same _company_id

So far I have this code:

$previous = '';

while ($result = $stmt->fetch()) {

    $current = $_company_id;

    //This should be executed every first iteration and every time $_company_id changes
    if ($current != $previous) { $html .= '<div id="company-' . $_company_id . '" class="tab-pane fade">'; }

    //Iterate all contact_id here with the same _company_id

    if ($current != $previous) { $html .= '</div>'; }

    $previous = $current;

}

My desired output is:

<div id="company-1" class="tab-pane fade">123</div>
<div id="company-2" class="tab-pane fade">45</div>

Right now the output is:

<div id="company-1" class="tab-pane fade">1</div>
23
<div id="company-2" class="tab-pane fade">4</div>
5

What should I change?

  • 写回答

2条回答 默认 最新

  • doumang20060820 2014-10-19 20:07
    关注
    $previous = null;
    
    while ($result = $stmt->fetch()) {
    
        $current = $_company_id;
    
        //This should be executed every first iteration and every time $_company_id changes
        if ($current !== $previous) {
          if($previous !== null)
            $html.='</div>';
          $html .= '<div id="company-' . $_company_id . '" class="tab-pane fade">';
        }
    
        //Iterate all contact_id here with the same _company_id
    
        $previous = $current;
    
    }
    
    if($previous!==null)
      $html.='</div>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度