I have a MySQL query that I am saving to a variable to output on the page. I have the data in an unordered list, but I am trying to split the data into three columns using 3 unordered lists floated left. Here is my current code:
$sqlCommand =
"SELECT list_specialty.id, list_specialty.specialty FROM list_specialty
ORDER BY list_specialty.specialty ASC";
$query = mysqli_query($myConnection,$sqlCommand) or die (mysqli_error($myConnection));
$specialtyDisplay = '';
$num = mysqli_num_rows($query);
$split = intval($num/3); //number of items in every column
$i = 0;
while ($row = mysqli_fetch_array($query)) {
$specialtyid = $row["id"];
$specialtyname = $row["specialty"];
$specialtyDisplay .=
'<li><a href="doctor.php?specialty=' . $specialtyid . '">' . $specialtyname . '</a></li>';
$i++;
if ($i == $split) {
$specialtyDisplay .= '</ul> <ul>';
$i = 0;
}
}
This code works GREAT as long as my data is exactly divisible by 3 (equal columns).
However, when my total number of rows is not divisible by 3, the above code won’t work.
I need a solution that will balance the columns, so I can have either 3 equal columns, one extra element in the first column, or one extra element in the first and second column.
What do I need to change in my code to account for that?
This will work:
$splitto the length of the longest column$longcols = $num % 3$splitwhen column number$longcolsis printed (unless all columns have equal length)Implemented in the code:
The lines with comments are those that I have changed/inserted.