1
0
mirror of https://github.com/processwire/processwire.git synced 2025-08-22 14:23:05 +02:00

Add WireArray::slices($qty) method that returns the WireArray sliced into $qty equal parts (new WireArray objects)

This commit is contained in:
Ryan Cramer
2018-11-09 14:26:32 -05:00
parent 32f594de2a
commit 96f62b313f

View File

@@ -2372,6 +2372,36 @@ class WireArray extends Wire implements \IteratorAggregate, \ArrayAccess, \Count
return $result === null ? $this : $result; 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 * Set the current duplicate checking state
* *