Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing up a dynamic number of items into columns

Tags:

php

pagination

I have a dynamic number of items in which I'll need to divide into columns. Let's say I'm given this:

array("one", "two", "three", "four", "five", "six", "seven", "eight")

I need to generate this:

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
</ul>
<ul>
  <li>five</li>
  <li>six</li>
  <li>seven</li>
  <li>eight</li>
</ul>

Here are some rules:

  • if there are no items, I don't want anything to be spat out
  • if there are 16 or under 16 items, id like 4 items per <ul>
  • if there are more than 16 items, i'd like it to be spread out evenly
  • i'll have to alphabetically reorder items. if there are 17 items, the 17th item will need to go to the first column but everything needs to be reordered.

What I have so far:

function divide( $by, $array ) {
 14     $total = count( $array );
 15     $return = array();
 16     $index=0;
 17     $remainder = $total % $by !== 0;
 18     $perRow = $remainder ?
 19         $total / $by + 1:
 20         $total / $by
 21         ;
 22 
 23     for ( $j = 0; $j<$by; $j++ ) {
 24         //$return[] = array();
 25 
 26         if ( $index == 0 ) {
 27             $slice = array_slice( $array, 0, $perRow );
 28             $index = $perRow;
 29             $return[$j] = $slice;
 30         } else {
 31             $slice = array_slice( $array, $index, $perRow );
 32             $index = $index+$perRow;
 33             $return[$j] = $slice;
 34         }
 35     }
}

I feed a number, like divide( 4, $arrRef ), the number dictates the # of columns, but I need to refactor so it determines the number of columns

like image 411
Reznor Avatar asked Dec 22 '22 20:12

Reznor


1 Answers

I used this code inside my view template..

<?php
$col = 3;
$projects = array_chunk($projects, ceil(count($projects) / $col));

foreach ($projects as $i => $project_chunk)
{
    echo "<ul class='pcol{$i+1}'>";
    foreach ($project_chunk as $project)
        {
        echo "<li>{$project->name}</li>";
    };
    echo "</ul>";
}; ?>
like image 137
cwouter Avatar answered Jan 09 '23 13:01

cwouter