I am reading directories with images for a website with the function dirToArray
.
I get for every directory one entry too much . This is named Array
, and the error appears. It appears for every directory. How can I get rid of this entry?
the function:
<?php
function dirToArray($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value){
if (!in_array($value,array(".","..","Array"))){
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
}else{
$result[] = $value;
}
}
}
return $result;
}
?>
My Code to read the directories:
<?php
$result=dirToArray("source");
foreach ($result AS $key => $value) {
$head = preg_replace('#_#',' ', $key);
echo '<h2>'.$head.'</h2>';
foreach ($value AS $subKey => $subValue) {
$titel = preg_replace('#_#',' ', subValue);
echo '<img src="backend/source/'.$key.'/'.$subValue.'" alt="'.$titel.'" />';
}
}
?>
Your loop to print $result
assumes it's a 2-dimensional array: everything in the top-level of the array is directories, and the 2nd level is all files. If you have more levels in your directory hierarchy, this will not be correct. dirToArray()
returns a nested hierarchy of arrays that mirrors the directory structure.
Therefore, you need a recursive function to print it, just like the recursive function you used to create it.
function printDirArray($dirname, $array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$head = str_replace('_', ' ', $key); // don't need `preg_replace` for ordinary characters
echo "<h2>$head</h2>";
printDirArray("$dirname/$head", $value);
} else {
$titel = str_replace('_', ' ', $value);
echo '<img src="backend/source/'.$dirname.'/'.$value.'" alt="'.$titel.'" />';
}
}
}
$result = dirToArray("source");
printDirArray("source", $result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.