user826855
user826855

Reputation: 598

Split Data into 3 columns

I have a MySQL table that contains people's names. Using PHP, what's the best way of dividing these names up and displaying them in 3 columns.

This could be achieved using an HTML table, but would it be possible to do this using only <div>'s?

I heard that this can be done using the % operator. Would this be the best way, and how would this be done?

Upvotes: 1

Views: 9272

Answers (1)

Bojangles
Bojangles

Reputation: 101473

You could do this using the modulus operator, however it's actually possible with just CSS.

Using display: inline-block, you can get a good column effect. Take a look at this JSFiddle here. I'm only using JavaScript because I'm lazy; the <div> list would be generated by PHP in your case. If you want to confine them to a certain width, just put them in a container <div> with a fixed width.


I've come up with a solution using tables, which is really what you should be doing (you haven't given any special use cases). The code is below, as well as a working demo here.

$columns = 4;       // The number of columns you want.

echo "<table>";     // Open the table

// Main printing loop. change `30` to however many pieces of data you have
for($i = 0; $i < 30; $i++)
{
    // If we've reached the end of a row, close it and start another
    if(!($i % $columns))
    {
        if($i > 0)
        {
            echo "</tr>";       // Close the row above this if it's not the first row
        }

        echo "<tr>";    // Start a new row
    }

    echo "<td>Cell</td>";       // Add a cell and your content
}

// Close the last row, and the table
echo "</tr>
</table>";

And to finish off, we have our column-centric layout, this time going back to divs. There's some CSS here; this should be put in a separate file, not left inline.

<?php
$rows = 10;     // The number of columns you want.
$numItems = 30;     // Number of rows in each column

// Open the first div. PLEASE put the CSS in a .css file; inline used for brevity
echo "<div style=\"width: 150px; display: inline-block\">";

// Main printing loop.
for($i = 0; $i < $numItems; $i++)
{
    // If we've reached our last row, move over to a new div
    if(!($i % $rows) && $i > 0)
    {
        echo "</div><div style=\"width: 150px; display: inline-block\">";
    }

    echo "<div>Cell $i</div>";      // Add a cell and your content
}

// Close the last div
echo "</div>";
?>

Upvotes: 8

Related Questions