[英]get all images in an array from directory and sub-directories
目前我類似於以下樹結構:
+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>
因為我對php非常陌生,所以我會盲目地在控制台中以Array()
身份登錄。
另外,我設置了$directory = "images/*/";
這將只獲取子文件夾中的所有圖像,但不能獲取可能為images/some-image.jpg
父目錄內的images/some-image.jpg
,我也想得到這個。
我希望像這樣的數組中的所有圖像(當我使用console.log(allImages);
)時:
['some-image.jpg','another.jpg','image1.jpg','image2.jpg','image3.jpg','image4.jpg']
我喜歡JSON ,讓事情變得簡單明了:
<?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>
現在你有了javascript中的php數組,具有相同的結構。 如果你有jQuery, $.each()
,你可以使用for
循環它們。
我將代碼更改為你的風格(混合php和html),但是你應該嘗試在htmltemplates中拆分它們。
我不是100%肯定這個,但你可以在你的glob中正則表達式,如果這工作你不需要foreach,這將只返回文件名:
$images = glob("~(?:images/*/)*\.jpg~");
那這個呢:
<script>
<?php
$directory = "images/*/";
$images = glob("" . $directory . "*.jpg");
echo "var allImages = ['".implode("', '", $images)."'];\n";
?>
console.log(allImages);
</script>
遞歸函數怎么樣?
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));
我在iPad上,所以我無法測試它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.