0

PHPはかなり新しいので、ここに質問があります。次の構造のSQL結果セットがあります。

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

ItemID = 0ごとに、テーブルを作成します。次に、ItemID = 0の下の各ItemIDについて、次のItemID = 0に到達するまで、新しいテーブルに行を作成します。最後まで繰り返します。

望ましい結果:

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

ItemID = 0のときに各テーブルを印刷することはできますが、それが正しい方法であるとは思えません。これが私がこれまでに持っているphpコードです:

$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( )?????
   }
4

2 に答える 2

1

このようなもの :

$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>';
}
于 2013-03-06T17:02:15.760 に答える
0

ifステートメントを少し変更するだけです。

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

そして、whileループの外側に、これを置きます:

print '</table>';

ループ構造全体は次のようになります。

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>';
于 2013-03-06T16:59:48.550 に答える