--- /dev/null
+<?php
+
+final class Collections
+{
+ /*
+ * Example output:
+ * 1 4 7 9
+ * 2 5 8 10
+ * 3 6
+ */
+ public static function columns($collection, $columnsCount)
+ {
+ $count = count($collection);
+ $r = $count % $columnsCount;
+ $length = ($count - $r) / $columnsCount;
+ $columns = array();
+ $offset = 0;
+ for ($i = 0; $i < $columnsCount; ++$i) {
+ $l = $length + ($i < $r ? 1 : 0);
+ $columns[] = array_slice($collection, $offset, $l);
+ $offset += $l;
+ }
+ return $columns;
+ }
+
+ public static function chunks($collection, $size, $pad=false)
+ {
+ $result = array();
+ $chunk = array();
+ foreach ($collection as $item) {
+ $chunk[] = $item;
+ if (count($chunk) === $size) {
+ $result[] = $chunk;
+ $chunk = array();
+ }
+ }
+ $c = count($chunk);
+ if ($c != 0) {
+ if ($pad)
+ while ($c < $size)
+ $chunk[] = null;
+ $result[] = $chunk;
+ }
+ return $result;
+ }
+}
+
--- /dev/null
+<?php
+
+class CollectionsTest extends PHPUnit_Framework_TestCase
+{
+ public function testColumns()
+ {
+ $arr = array(
+ 'apple',
+ 'grapefruit',
+ 'carrot',
+ 'tomato',
+ );
+ $columns = Collections::columns($arr, 3);
+ $this->assertEquals(3, count($columns));
+ $this->assertEquals(2, count($columns[0]));
+ $this->assertEquals(1, count($columns[1]));
+ $this->assertEquals(1, count($columns[2]));
+ }
+
+ public function testChunks()
+ {
+ $arr = array(
+ 'apple',
+ 'grapefruit',
+ 'carrot',
+ 'tomato',
+ );
+ $chunks = Collections::chunks($arr, 3);
+ $this->assertEquals(2, count($chunks));
+ $this->assertEquals(3, count($chunks[0]));
+ $this->assertEquals(1, count($chunks[1]));
+ }
+}
+