Get all images in an array from a directory and subdirectories

I currently look like 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> 

Since I'm extremely new to php, I blindly register as Array() in the console.

In addition, I set $directory = "images/*/"; , which will receive all images only inside subfolders, but not receiving images inside the parent directory, which can be set to images/some-image.jpg , and I also wanted to get this.


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

 ['some-image.jpg','another.jpg','image1.jpg','image2.jpg','image3.jpg','image4.jpg'] 
+5
source share
3 answers

I love JSON , keeps things beautiful 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 a php array available in javascript with the same structure. You can encode them with for if you have jQuery, $.each() .
I changed the code more to your style (mixing php and html), but you should try to break them down into htmltemplates.


I'm not 100% sure, but you can regex in your glob, if that works, you don't need foreach, it will only return file names:

 $images = glob("~(?:images/*/)*\.jpg~"); 
+3
source

How about this:

 <script> <?php $directory = "images/*/"; $images = glob("" . $directory . "*.jpg"); echo "var allImages = ['".implode("', '", $images)."'];\n"; ?> console.log(allImages); </script> 
0
source

What 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 am on an iPad, so I canโ€™t check it.

0
source

Source: https://habr.com/ru/post/1208684/


All Articles