简体   繁体   中英

php multiple alternate column loop

im very new to php and html and im trying to create an ouput like this coming from a database table recordset. where "table record n" is the column from the db table record set

basically the table will be a 1x2x1x2x4 columns with 5 rows

<table border=1>
    <tr> 
        <td>table record 1 </td>
    </tr>

    <tr> 
        <td> table record 2 </td> <td>table record 3 </td>
    </tr>   
    <tr> 
        <td> table record 4 </td>
    </tr>
    <tr> 
        <td> table record 5 </td> <td>table record 6 </td>
    </tr>
    <tr> 
        <td> table record 7 </td> 
        <td>table record 8 </td>
        <td> table record 9 </td> 
        <td>table record 10</td>
    </tr>

</table>

i only got as far as this one

          $next_Column = 1;


          echo "<tr>";

           while ( $row = mysql_fetch_array( $result ) ) 
           { 
    echo "<td>". $row['name']. "</td>"; 
    $next_Column ++;

    if( $next_Column > 1 )
    {
        echo "<tr>";
        $next_Column = 1;
    }
       } 
          ?> 

The above loop will always echo a <tr> , because when you get to the if , $next_column will always be > 1. You need to use nested loops to loop through the columns. Something like the code on this page should help. Although, if you KNOW you need it in that exact format, why not just make your php like this?

<table border=1>
<?php
    while ( $row = mysql_fetch_array( $result ) )
    {
        echo '<tr><td>' . $row[0] . '</td></tr>';
        echo '<tr><td>' . $row[1] . '</td><td>' . $row[2] . '</td></tr>';
        echo '<tr><td>' . $row[3] . '</td></tr>';
        echo '<tr><td>' . $row[4] . '</td><td>' . $row[5] . '</td></tr>';
        echo '<tr><td>' . $row[6] . '</td><td>' . $row[7] . '</td>';
        echo '<td>' . $row[8] . '</td><td>' . $row[9] . '</td></tr>';
    }
?>
</table>

Note that all those numbers can be replaced with column names in quotes (like 'name' ). Also, the above code will emit 5 table rows for EVERY ROW in the database. Is that what you are looking to do?

EDIT: If you are trying to loop through each row and add it to a table based on THAT ROWS number of columns, then I would suggest something like this:

<table border=1>
<?php
    while ( $row = mysql_fetch_array( $result ) )
    {
        echo '<tr>';

        //Loop through cols
        foreach($row as $value)
        {
            if($value)
            {
                echo '<td>' . $value . '</td>';
            }
        }

        echo '</tr>'
    }
?>
</table>

This will put the value in the table row ONLY IF it is in the database, so if you have a row with 1 filled column, you get 1 table column, but a row with 4 columns filled will have 4 table columns.

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