Print new <div> on id iteration change inside php while loop from MySQL result

自作多情 提交于 2019-12-13 07:35:24

问题


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?


回答1:


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



回答2:


Can you post your SQL query and/or some more code in this example. Off the top of my head, you could do something like:

<?php
$dbh = new PDO("mysql:host=localhost;dbname=companies","root","root");
$sql = "select _company_id from table_name limit 0,30;";
$companies = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
foreach($companies as $company){
    $contacts_sql = "select contact_id from table_name where company_id = :company_id";
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(":company_id", $company['_company_id'], PDO::PARAM_INT);
    $stmt->execute();
    $contacts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "<div id='company-{$company['_company_id']}'>";
    foreach($contacts as $contact){
        echo $contact['contact_id'];        
    }
    echo "</div>".PHP_EOL;
}
?>

Could you not?



来源:https://stackoverflow.com/questions/26454774/print-new-div-on-id-iteration-change-inside-php-while-loop-from-mysql-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!