简体   繁体   中英

Displaying tables results in multiple columns, column by column

I have displayed my results in a table with 5 columns. The results read across the page then a <TR> starts a new line and the next row of results is displayed (see http://www.dsoba.co.uk/immemoriam/index2.php ) Can I display them to first fill a column then the next column? Its easier to scan a column than a row.

            $result = mysqli_query($con,"SELECT * FROM memberlist where deceased='d' order by surname, initials");
            $tmp = 0; # initiate the tmp variable
    echo "<table class='table1'>
            <tr>";
        while($row = mysqli_fetch_array($result))
             {  # start of the while loop, once for each record

                # note removed the <BR> from the main output of the loop:
    echo "<td>" . $row['initials'] . " " . $row['surname'] . " " . $row['yearstart'] . " - " . $row['yearleft'] . "</td>";
        $tmp = ++$tmp; # increment 'tmp' by 1
        if ($tmp == 5)  {
        $tmp = 0;
    echo "</tr><tr>";  # new line if you've echoed 5 records
                        }

             }    # this is the end of the while loop


    echo "</tr></table>";

You can save your data into arrays per column.

$columns = [];
$i = 0;
while($row = mysqli_fetch_array($result)) {
    $columns[$i++ % INT_COLUMNS][] = $row;
}

foreach ($i = 0; $i < count($columns[0]); $i++) {
    echo '<tr>';
    foreach ($j = 0; $j < INT_COLUMNS; $j++) {
        if (isset($columns[$j][$i]) {
            echo '<td>...</td>';
        }
    }
    echo '</tr>';
}

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