目前我类似于以下树结构:
+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
父目录中的图像,我也想得到这个。
我想要这样的数组中的所有图像(当我使用 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数组,具有相同的结构。你可以用一个for
循环它们,如果你有jQuery,$.each()
。
我根据您的风格更改了代码(混合 php 和 html),但您应该尝试在 htmltemplate 中拆分它们。
我不是 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上,所以我无法测试它。