【问题标题】:PHP get all images with prefix 1_, 2_, 3_ etc. if they exist in folderPHP 获取所有带有前缀 1_、2_、3_ 等的图像(如果它们存在于文件夹中)
【发布时间】:2018-06-21 16:20:15
【问题描述】:

目标: 获取前缀为 1_、2_、3_ 等的所有图像(如果它们存在于文件夹中)

问题: 图像名称由 db while 循环动态添加。这将返回:13848。但我需要检索:13848.jpg、1_13848.jpg、2_13848.jpg、3_13848.jpg(如果存在)。 如何检查并返回与此模式存在的图像。

图片名称与product_id 相同。 我正在从数据库查询中获取名称/id 部分。

我现有的图片:

folder_name/13848.jpg
folder_name/1_13848.jpg
folder_name/2_13848.jpg
folder_name/3_13848.jpg

我的努力:

function imageExists($image,$dir) {
$i=1; $try=$image;

while(file_exists($dir.$probeer)) {
    if($image[1] != "_") {
    $try= $i. "_" . $image;
} 
else {
    $try=$image;
    }
$i++;
}

return $try;
}

像这样使用它:

while ($r = $q->fetch()) {

$image_folder = "folder_name/";
$image_id = $r['product_id'].".jpg";
$new_imagePath = $image_folder . imageExists($image_id,$image_folder);

echo "<a href='". $imagePath ."'><img class='product' height='' src='". $new_imagePath ."' alt='". $r['product_id']  ."-".  str_replace("'", "", $r['product_name']) . "' title='". str_replace("'", "", $r['product_name']) ."' /></a>";

}

现在它返回不存在的图像: 文件夹名称/4_13848.jpg

【问题讨论】:

  • 你有什么问题?
  • 图像名称由 db while 循环动态添加。这将返回:13848。但我需要检索:1_13848.jpg、2_13848.jpg、3_13848.jpg 等(如果存在)。感谢您的努力

标签: php file exists


【解决方案1】:
 $files = glob('FOLDER_PATH/*.{jpg}',GLOB_BRACE);
 function image_exist($files){

  foreach($files as $file){ //retrieves all file name in specified folder
    if (strpos($file, '_') !== false){ //Checks 1_567898.jpg type file exist
       return true;
    }
    else{
       return false;
    }
   }
 }

【讨论】:

  • 欢迎来到 SO 并感谢您的贡献。考虑在您的答案中添加文本注释,而不仅仅是 sn-p。
  • @Heena,感谢您的努力,但它只会返回 true 或 false。图像是动态添加的。请参阅我帖子中的问题。我正在检查 db cal 的返回,而不是带有图像的文件夹。
猜你喜欢
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 2020-07-18
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多