Last active
August 29, 2015 14:04
-
-
Save dlundgren/d5c98c61e40580d889c9 to your computer and use it in GitHub Desktop.
Partitions an array. Similar to array_chunk but goes through the array linearly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Partitions the array in a linear fashion. | |
* | |
* This is similar to array_chunk | |
* | |
* @param array $ary The array to partition | |
* @param int $partitions How many partitions should the array be split into. | |
* Default is to calculate off of the input array length | |
* @return array | |
*/ | |
function array_partition(array $ary, $partitions = null) { | |
$ret = array(); | |
$keys = array_keys($ary); | |
$length = count($keys); | |
if ($partitions === null) { | |
$partitions = round($length / 2); | |
} | |
for ($i = 0; $i < $length; ++$i){ | |
$ret[$i % $partitions][] = $ary[$keys[$i]]; | |
} | |
return $ret; | |
} |
Author
dlundgren
commented
Jul 23, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment