Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Split a array into semi-equal sized chunks
<?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 <branmovic@gmail.com>
* @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;
}
<?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>';
<?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
You can’t perform that action at this time.