I'm not even sure if I am writing this code as efficiently as possible but I'm stuck and need help...
HTML
<?php
echo outputDirArray($dir_array, 0, '');
?>
In PHP, I have a function to put my directories into an array:
function dirToArray($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value,array('.','..'))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
$result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
} else {
$result[] = $value;
}
}
}
return $result;
} //Thanks to someone on this site for this function
I then take that array and pass it to another function to output it the way I need it to:
function OutputDirArray(&$arr, $x, $origName) {
$str;
foreach ($arr as $key => $value) {
if($x == 0) $origName = $key;
if (is_array($value)) {
if($x > 0) $str .= '</div>';
$str .= '<div class="infoDiv clearfix"><span class="title">'.$key.'</span><br/>'.OutputDirArray($value, ++$x, $origName).'</div>';
--$x;
} else {
if($x > 0) {
$str .= '<div class="displayImgs"><img src="images/'.$origName.'/'.$value.'"/></div>';
} else {
$str .= '<div class="infoDiv clearfix"><span class="title">Profile Picture</span>
<div class="displayImgs"><img src="images/'.$value.'"/></div></div>';
}
}
}
return $str;
}
My var_dump($dir_array);
output:
array(3) { [0]=> string(7) "img1.jpg" ["test1"]=> array(4) { [0]=> string(15) "subimg1.gif" [1]=> string(9) "subimg2.png" [2]=> string(9) "subimg3.jpg" ["test3"]=> array(3) { [0]=> string(15) "subsubimg1.gif" [1]=> string(9) "subsubimg2.png" [2]=> string(9) "subsubimg3.jpg" } } ["test2"]=> array(3) { [0]=> string(15) "subimg1.gif" [1]=> string(9) "subimg2.png" [2]=> string(9) "subimg3.jpg" } }
What am I trying to do here is take in the dir_array and walk through outputting the html code. Everything seems to work fine except for two problems...
1) If I have a subsub directory, $key in <span class="title">'.$key.'</span>
outputs the correct key (in my case, test3). However $origName in <img src="images/'.$origName.'/'.$value.'"/>
outputs the original key used (test1).
2) I believe because of my subsub dir problem, I am left with an extra </div>
after the subsub (test3) outputs.
It's been too long now trying to figure this out, so any help is greatly appreciated.