From 96f62b313fca3f48df0521096145b782fa08c0e3 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 9 Nov 2018 14:26:32 -0500 Subject: [PATCH] Add WireArray::slices($qty) method that returns the WireArray sliced into $qty equal parts (new WireArray objects) --- wire/core/WireArray.php | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/wire/core/WireArray.php b/wire/core/WireArray.php index 7dbf3513..8f29a72a 100644 --- a/wire/core/WireArray.php +++ b/wire/core/WireArray.php @@ -2372,6 +2372,36 @@ class WireArray extends Wire implements \IteratorAggregate, \ArrayAccess, \Count return $result === null ? $this : $result; } + /** + * Divide this WireArray into $qty slices and return array of them (each being another WireArray) + * + * This is not destructive to the original WireArray as it returns new WireArray objects. + * + * #pw-group-retrieval + * #pw-group-traversal + * + * @param int $qty Number of slices + * @return array Array of WireArray objects + * + */ + public function slices($qty) { + $slices = array(); + if($qty < 1) return $slices; + $total = $this->count(); + $limit = $total ? ceil($total / $qty) : 0; + $start = 0; + for($n = 0; $n < $qty; $n++) { + if($start < $total) { + $slice = $this->slice($start, $limit); + } else { + $slice = $this->makeNew(); + } + $slices[] = $slice; + $start += $limit; + } + return $slices; + } + /** * Set the current duplicate checking state *