php遍歷資料夾以及子目錄
<?php
function my_dir($folderPath){
$arr_subdictory = array();
if (@$handle = opendir($folderPath)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) { // 排除更目錄
if (is_dir($folderPath ."/". $entry)) { // 如果是子資料夾,就進行遞迴;
$arr_subdictory[$entry] = my_dir($folderPath. "/" . $entry);
} else {
$arr_subdictory[] = $folderPath ."/". $entry;
}
}
}
closedir($handle);
return $arr_subdictory;
}
}
function flattenArray($array) {
$result = array();
foreach ($array as $item) {
if (is_array($item)) {
$result = array_merge($result, flattenArray($item));
} else {
$result[] = $item;
}
}
return $result;
}
$folderPath = 'D:/ssdf/dda/agag'; // 替換為你的資料夾路徑
$arr_end = my_dir($folderPath);
$arr_result = flattenArray($arr_end ); // 將多餘維多陣列變成一維陣列;
echo $arr_result[array_rand($arr_result )]; // 隨機返回一條記錄;