0

I would like to iterate through folders and write all the .jpg files to a array in order to use them in the next step to create a time-lapse slideshow.

Below is the code that I already have, but how can I :

  1. Write the $file to a array?
  2. Access it from jQuery for later processing?

My code so far:

<?php
$dir ="files";
$i=0;
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($dir)
);
$jpg_files = new RegexIterator($iterator, '/\.jpg$/'); // Dateiendung ".jpg"

foreach ($jpg_files as $file) {
    if (!$file->isFile()) {
        continue;
    }
    # echo $file->getPathname() . "\n";
    ?>
            <img src="<?php echo $file;?>"/>
    <?php
}
François Maturel
  • 5,884
  • 6
  • 45
  • 50
cschirra
  • 3
  • 3

1 Answers1

0

In your loop, instead of outputting the file with <img src="<?php echo $file;?>"/>, append it to an array:

foreach ($jpg_files as $file) {
    if (!$file->isFile()) {
        continue;
    }
    $files[] = "$file";            // appends to $files array
}

You can use json_encode to convert the array to a format JQuery can use. There are various ways to get it into your JS environment. One way:

echo '<script> var files = ' . json_encode($files) . '</script>';
Community
  • 1
  • 1
Don't Panic
  • 41,125
  • 10
  • 61
  • 80