简体   繁体   中英

PHP - loop through SQL resultset. When condition met repeat

Pretty new to PHP so here's the question. I have a SQL resultset with the following structure:

ItemID Desc
0      A
1      B
2      C
0      D
3      E
0      F
4      G
5      H

For each ItemID = 0 I want to create a table. Then for each ItemID under ItemID = 0, I want to create a row in a new table, until I hit the next ItemID = 0. Repeat until end.

Desired results:

<table>
    <tr>
        <td>A</td>
    </tr>
</table>
<table>
    <tr>
        <td>B</td>
    </tr>
    <tr>
        <td>C</td>
    </tr>
</table>
<table>
    <tr>
        <td>D</td>
    </tr>
</table>
<table>
    <tr>
        <td>E</td>
    </tr>
</table>
<table>
    <tr>
        <td>F</td>
    </tr>
</table>
<table>
    <tr>
        <td>G</td>
    </tr>
    <tr>
        <td>H</td>
    </tr>
</table>

I can get each table to print when ItemID = 0, but doubt it's the correct method. Here's the php code I have so far:

$legendSql="select ItemID, Desc from ...";
$getLegend=sqlsrv_query($conn, $legendSql);
while( $row = sqlsrv_fetch_array( $getLegend, SQLSRV_FETCH_ASSOC) ) {
    if ($row['ItemID'] === '.00') { // when ItemID = 0 create table
        print '<table>';
        print '<tr>';
        print '<td>';
        print $row['Desc'];
        print '</td>';
        print '</tr>';
        print '</table>';
    }
//    foreach( )?????
   }

Something like this :

$first=1;

while( $row = sqlsrv_fetch_array( $getLegend, SQLSRV_FETCH_ASSOC) )
  {

    if ($row['ItemID'] === '.00') // when ItemID = 0 create table
    {
      if ($first==0)
      {
        print '</table>';
      }
      print '<table>';
      print '<tr>';
      print '<td>';
      print $row['Desc'];
      print '</td>';
      print '</tr>';
      print '</table>';
      $first=1;
    }
    else
    {
      if ($first==1)
      {
        print '<table>';
        $first=0
      }
      print '<tr>';
      print '<td>';
      print $row['Desc'];
      print '</td>';
      print '</tr>';
    }
}
if ($first==0)
{
  print '</table>';
}

Just change your if statement slightly:

if ($row['ItemID'] === '.00') { // when ItemID = 0 create table
    print '<table>';
}
print '<tr>';
print '<td>';
print $row['Desc'];
print '</td>';
print '</tr>';

And outside the while loop, put this:

print '</table>';

The entire loop structure becomes:

while( $row = sqlsrv_fetch_array( $getLegend, SQLSRV_FETCH_ASSOC) ) {
    if ($row['ItemID'] === '.00') {
        print '<table>';
    }
    print '<tr>';
    print '<td>';
    print $row['Desc'];
    print '</td>';
    print '</tr>';
}
print '</table>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM