Cleaner way of using modulus for columns
I currently have a list (<ul>) of people that I have divided up into two columns. But after finishing the code for it I keept wondering if there is a more effective or clean way to do the same thing.
echo "<table class='area_list'><tr>";
// Loop users within areas, divided up in 2 columns
$count = count($areaArray);
for($i=0 ; $i<$count ; $i++) {
  $uid = $areaArray[$i];
  // get the modulus value + ceil for uneven numbers
  $rowCalc = ($i+1) % ceil($count/2);
  if ($rowCalc == 1) echo "<td&g开发者_开发知识库t;<ul>";
  // OUTPUT the actual list item
  echo "<li>{$users[$uid]->profile_lastname}</li>";
  if ($rowCalc == 0 && $i!=0) echo "</ul></td>";
}
echo "</tr></table>";
Dont know whether this is what @llia meant, but what about have the for loops like this:
//declare how many columns are needed
$cols=2;
//iterate over each row of entries (down the column)
for ($i=0;i<$count;i+=cols){ 
     echo "<td><ul>";
     //entry loop (across the row)
     for($j=0;j<$cols;j++){ 
           //whose line is it anyway?
           $uid = $areaArray[$i+$j];
           echo "<li>{$users[$uid]->profile_lastname}</li>";
     }
     //end entry loop
     echo "</ul></td>";
}
//end row loop
that way, you can set however many columns you like.
Forgive me if I missed something as I'm waiting for the kettle to boil to get my much needed caffine!
This should do what you want. I pretty much just combined the other two answers so +1 for everyone.
$cols=3;
$user_count = count($users);
echo "<table class='area_list'><tr>";
// Column loop
for($i=0;$i<$cols;$i++){
    echo "<td><ul>";
    // user loop
    for($j=$i;$j<$user_count;$j+=$cols){
        echo "<li>{$users[$j]->profile_lastname}</li>";
    }
    echo "</ul></td>";
}
echo "</tr></table>";You can just loop twice, once for each column. Start at 0 in the first column and at 1 in the second. Increment by two.
Edit: To make it even nicer, put the columns themselves in a loop:
$cols = 3;
echo '<table><tr>';
// column loop
for ($c = 1; $c <= $cols; $c++) {
  echo '<td><ul>';
  // item loop
  for ($i = 0; $i < count($areaArray); $i += $c) {
     echo '<li>...</li>';
  }
  echo '</ul></td>';
}
echo '</tr></table>';
$cols = 3;
$chunkSize = ceil(count($areaArray) / $cols);
echo $chunkSize * $cols;
foreach (array_chunk($areaArray, $chunkSize) as $items) : ?>
 <td>
  <ul>
<?php foreach ($items as $item) : ?>
   <li><?php echo $item ?></li>
<?php endforeach; ?>
  </ul>
 </td>
<?php endforeach; ?>
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论