[英]Scan multiple image directories in PHP
我嘗試使用 PHP 掃描多個圖像目錄並創建一個數組,其中包含每個圖像的確切路徑及其名稱。
示例目錄樹
main/
├─ sub-directory-1/
│ ├─ image1.png
│ ├─ image2.jpeg
│ ├─ image3.png
├─ sub-directory-2/
│ ├─ image1.png
├─ sub-directory-3/
│ ├─ image1.jpeg
│ ├─ imageX.png
所需數組的示例
{
0 : {name: "image1", path: "main/subdirectory-1/image1.png"},
1 : {name: "image2", path: "main/subdirectory-1/image2.jpeg"},
2 : {name: "image3", path: "main/subdirectory-1/image3.png"},
.
.
.
7 : {name: "imageX", path: "main/subdirectory-3/imageX.png"},
}
這是讓我得到預期結果的方法。
我希望這會對某人有所幫助
public function ImageScanner() {
$current_dir = getcwd();
$folderpath = 'PATH/TO/SOME/DIR/';
// Determining if the path is a directory or not
if (is_dir($folderpath)) {
// Opening the directory
$files = opendir($folderpath); {
// Checking if the directory opened
if ($files) {
//Reading each element's name in the directory
while (($subfolder = readdir($files)) !== false) {
// Checking for errors in filename
if ($subfolder != '.' && $subfolder != '..') {
$dirpath = 'SOME/SUB_DIR/PATH/' . $subfolder . '/';
// Checking and opening each file inside the sub directory
if (is_dir($dirpath)) {
$file = opendir($dirpath);
if ($file) {
// Reading each element's name in the sub directory
while (($filename = readdir($file)) !== false) {
if ($filename != '.' && $filename != '..') {
$image_path = '' . $dirpath . '' . $filename . '';
// Creating array for each scanned file
$key = array(
'image_name' => trim($filename) ,
'image_path' => str_replace('/SOME/PATH/', '', $image_path) ,
);
// Appending each image array
$image_arrays[] = $key;
}
}
}
}
}
}
}
}
}
return $image_arrays;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.