问题基本上在标题中。获取目录中第一个"jpg"图像的路径的最有效的PHP方法是什么?
通常情况下,在目录中只会有一个图像,但如果有更多,我需要确保它只得到一个(无论哪个)。
非常感谢。
试试这个,$imagePaths
将包含所有的图像路径,但是只需调用数组中的第一个键来获取一个。
$imageDirectory = "path/to/your/image/dir/";
$imagePaths = [];
foreach (glob($imageDirectory . "*.jpg") as $image) {
array_push($imagePaths, $image);
}
// $imagePaths[0] => First image path.
编辑1
转换成函数可以是这样简单的东西
<?php
function getImagePaths($dir = "")
{
// Shorthand if statement to see if $dir is not empty, if it is not we set the parameter value to the $imageDirectory we want to use, otherwise use a default image directory which was specified.
$imageDirectory = !empty(trim($dir)) ? $dir : "default/path/to/your/image/dir/";
$imagePaths = [];
foreach (glob($imageDirectory . "*.jpg") as $image) {
array_push($imagePaths, $image);
}
if (!empty($imagePaths)) return $imagePaths;
return false;
}
?>
阅读材料:
glob
PHP有opendir()
, closedir()
和readdir()
函数,您可以使用这些函数并在找到第一个文件后跳出