Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get all images in an array from directory and sub-directories

Tags:

javascript

php

Currently I've similar to the following tree structure:

+images
    +sub-directory
       -image1.jpg
       -image2.jpg
    +sub-directory-2
       -image3.jpg
       -image4.jpg
    -some-image.jpg
    -another.jpg

<script>
<?php
//path to directory to scan. i have included a wildcard for a subdirectory
$directory = "images/*/";

//get all image files with a .jpg extension.
$images = glob("" . $directory . "*.jpg");

$imgs = '';
// create array
foreach($images as $image){ $imgs[] = "$image"; }
echo "var allImages = ".$imgs.";\n";
?>

console.log(allImages);
</script>

As I'm extremely new to php, I'm blindly getting logged as Array() in the console.

Also, I've set $directory = "images/*/"; which will get all images inside the subfolders only but not getting images inside parent directory that likely to images/some-image.jpg and I wanted to get this too.


I want all the images in an array like this (when I use console.log(allImages);):

['some-image.jpg','another.jpg','image1.jpg','image2.jpg','image3.jpg','image4.jpg']
like image 806
Bhojendra Rauniyar Avatar asked Dec 09 '14 19:12

Bhojendra Rauniyar


3 Answers

I love JSON, keeps things nice and simple:

<?php
$images = glob("images/*/*.jpg");
$imgs = array();
foreach($images as $image){ $imgs[] = $image; }
?>
<script>
    var allImages = JSON.parse('<?php echo json_encode($imgs);?>');
    console.log( allImages);
</script>

Now you have the php array available in javascript, with the same structure. You can loop them with a for, of if you have jQuery, $.each().
I changed a code more to your style (mixing php and html), but you should try to split those in htmltemplates.


Im not 100% sure about this, but you can regex in your glob, if this works you don't need the foreach, this will return only the filenames:

$images = glob("~(?:images/*/)*\.jpg~");
like image 82
Martijn Avatar answered Nov 09 '22 15:11

Martijn


What about this:

<script>

<?php

$directory = "images/*/";

$images = glob("" . $directory . "*.jpg");

echo "var allImages = ['".implode("', '", $images)."'];\n";

?>

console.log(allImages);

</script>
like image 40
erikvimz Avatar answered Nov 09 '22 16:11

erikvimz


How about a recursive function?

function loadImages($folder)
{
    $files = glob($folder);
    foreach( $files as $file )
    {
        if(is_dir($file))
        {
            loadImages($file);
        } else {
            $images[] = $file; // add some file type validation here
        }
    }

    return $images;
}

$images = json_encode(loadImages($startFolderPath));

I'm on an iPad so I can't test it.

like image 1
DevDonkey Avatar answered Nov 09 '22 15:11

DevDonkey