I'm using DirectoryIterator to list files. In this scenario my dir contains 19 files.
I need to create a list which wraps 7 files into a <div>
.
I must be tired, because I'm not able to do this simple task.
My code is updated to reflect suggestions below:
$i = 0;
echo '<div class="first_div">';
foreach ($dir as $fileinfo) {
if ($fileinfo->isFile()) {
if(($i % 7 == 0) && ($i > 0) )
echo '</d开发者_StackOverflow中文版iv><div>';
echo 'My file';
$i++;
}
}
echo '</div>';
Any help appreaciated.
Something along these lines:
echo '<div>';
$i = 0;
foreach ($dir as $fileinfo) {
if($i % 7 == 0 && $i != 0) {
echo '</div><div>';
}
// do stuff
$i++;
}
echo '</div>';
or ssomething like
$chunk_size = 7;
foreach (array_chunk($dir, $chunk_size) as $chunk) {
echo '<div>';
foreach ($chunk as $fileinfo) {
// echo list item $fileinfo here
}
echo '</div>';
}
Try using the mod operator (%) to determine if the current file number is the 7th one:
echo "<div>";
$i = 0;
foreach ($dir as $fileinfo) {
// Remainder is 0, so its the first of 7 files.
// Skip this for the first one, or we'll get a blank div to start with
if($i % 7 == 0 && $i>0) echo "</div><div>";
echo $filenamehere;
$i++;
}
echo "</div>";
(Code is untested but should work)
EDIT : Used an independent counter for $i, since the index seemed to start at 2 and not 0 as expected.
Somesthing similar to this:
$c = 0;
foreach ($files as $file) {
echo $file;
if ($c % 7 == 0) {
//7th file
}
$c++;
}
Using mod 7
$counter += 1;
if($counter % 7 = 0)
//New div
Not 100% sure on syntax for this i Php but ther must be some
You can use array_chunk() function to split an array to chunks.
<?
$dir_chunks = array_chunk($dir, 7);
foreach($dir_chunks as $dir)
{
echo '<div>';
foreach ($dir as $fileinfo) {
if ($fileinfo->isFile()) {
// build list here
}
}
echo '</div>';
}
?>
Or (throwing out the % operator and putting in more SPL)
<?php
$path = '......';
$nrit = new NoRewindIterator(new DirectoryIterator($path));
while ( $nrit->valid() ) {
echo "<div>\n";
foreach( new LimitIterator($nrit, 0, 7) as $it ) {
echo ' ', $it, "\n";
}
echo "</div>\n";
}
Use this code:
if(($i-2) % 7 == 0)
精彩评论