From: Andrey Kutejko Date: Sun, 22 Sep 2013 19:32:38 +0000 (+0300) Subject: more generic code in Collections::columns X-Git-Tag: 0.1~10 X-Git-Url: https://git.andy128k.dev/?a=commitdiff_plain;h=f13fbb42d0d1a54bd709d374abfbcab63c18f7f7;p=missing-tools.git more generic code in Collections::columns --- diff --git a/src/collectiontools.php b/src/collectiontools.php index b2bfc04..eb2a42d 100644 --- a/src/collectiontools.php +++ b/src/collectiontools.php @@ -13,13 +13,23 @@ final class Collections $count = count($collection); $r = $count % $columnsCount; $length = ($count - $r) / $columnsCount; - $columns = array(); - $offset = 0; + + $columnLengths = array(); for ($i = 0; $i < $columnsCount; ++$i) { - $l = $length + ($i < $r ? 1 : 0); - $columns[] = array_slice($collection, $offset, $l); - $offset += $l; + $columnLengths[] = $length + ($i < $r ? 1 : 0); + } + + $column = array(); + $columnIndex = 0; + foreach ($collection as $item) { + if (count($column) >= $columnLengths[$columnIndex]) { + $columns[] = $column; + $column = array(); + $columnIndex++; + } + $column[] = $item; } + $columns[] = $column; return $columns; }