Created
May 2, 2011 16:18
-
-
Save branneman/951858 to your computer and use it in GitHub Desktop.
Split a array into semi-equal sized chunks
This file contains hidden or 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 | |
/** | |
* Split a array into semi-equal sized chunks. | |
* A so-called 'columnizer' | |
* | |
* @param array $array The array to split | |
* @param array $numberOfChunks The number of chunks | |
* @param bool $vertical Whether to order vertically or horizonally | |
* | |
* @return array Array with $numberOfColumns nodes with items of $array | |
* | |
* @author Bran van der Meer <[email protected]> | |
* @since 08-02-2010 | |
*/ | |
function arrayEqualChunks($array, $numberOfChunks = 2, $vertical = true) | |
{ | |
if ($vertical) { | |
$perColumn = floor(count($array) / $numberOfChunks); | |
$rest = count($array) % $numberOfChunks; | |
$perColumns = array(); | |
for ($i = 0; $i < $numberOfChunks; $i++) { | |
$perColumns[$i] = $perColumn + ($i < $rest ? 1 : 0); | |
} | |
foreach ($perColumns as $rows) { | |
for ($i = 0; $i < $rows; $i++) { | |
$data[$i][] = array_shift($array); | |
} | |
} | |
} else { | |
$i = 0; | |
foreach ($array as $node) { | |
$data[$i][] = $node; | |
$i = ($i >= ($numberOfChunks - 1) ? 0 : $i + 1); | |
} | |
} | |
return $data; | |
} |
This file contains hidden or 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 | |
// Vertical example | |
echo '<pre style="background-color:#aaf">'; | |
$data = arrayEqualChunks(range(1, 31), 7); | |
foreach ($data as $row) { | |
foreach ($row as $node) { | |
printf('[%2s]', $node); | |
} | |
echo "\n"; | |
} | |
echo '</pre>'; |
This file contains hidden or 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 | |
// Horizontal example | |
echo '<pre style="display:table;width:100%;background-color:#afa">'; | |
$data = arrayEqualChunks(range(1, 33), 5, false); | |
foreach ($data as $col) { | |
echo '<div style="float:left;width:20%">'; | |
foreach ($col as $node) { | |
printf("%2s\n", $node); | |
} | |
echo '</div>'; | |
} | |
echo '</pre>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment