Cleaner way of using modulus for columns

后端 未结 4 1897
一个人的身影
一个人的身影 2021-01-26 10:31

I currently have a list (

    ) 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 cle
相关标签:
4条回答
  • 2021-01-26 11:08

    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!

    0 讨论(0)
  • 2021-01-26 11:08

    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>';
    
    0 讨论(0)
  • 2021-01-26 11:13
    $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; ?>
    
    0 讨论(0)
  • 2021-01-26 11:16

    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>";
    0 讨论(0)
提交回复
热议问题