Chunk arrays with php
For a while now I have been using a bit of code for reading the contents of a directory, pushing the found items into an array, then looping over the array with a foreach to create markup for a slideshow, header images, backgrounds, etc. A current project I am working on needs this same functionality but with a twist. I still need to loop over the directory but I need to group the contents into groups or chunks. Enter, PHP’s array_chunk(). This does exactly what I need, but to get the array’s contents neatly on screen I am nesting a set of foreach loops. One for the first subarray, then the other for that subarray’s contents. It goes something like this:
// Initialize the array to hold images
$thelist = array();
// Open directory and add files into array
if ($handle = opendir($dir_path)) {
// Loop over the directory.
while (false !== ($file = readdir($handle))) {
// Don't include the "." and
// ".." files. As well as the
// DS_Store files left by the Mac OS
if ( $file != "." && $file != ".." && $file != ".DS_Store" ) {
array_push($thelist,$file);
}
}
closedir($handle);
}
natsort($thelist); // Put the array in alphabetical order
//shuffle($thelist); // Put the array in random order
// Split array into chunks
$subarray = (array_chunk($thelist, 5));
// Layout the contents
echo "<ul>\n";
foreach ($subarray as $arraygroup) {
echo "<li>";
foreach ($arraygroup as $arrayitem) {
// Do pretty markup here
echo "<p>Item: $arrayitem</p>";
} // END nest
echo "</li>";
} // END main
echo "</ul>\n";
Published on August 31, 2011