前一陣時間面試XX公司筆試題中竟然有這樣一道題:
使用PHP列出目錄樹!
當時一看就懵逼了!基本的想法還是有的,不過是使用遞歸演算法,但對PHP操作目錄檔的方法卻不是很了解,所以今天好好補習一下!
解題思路:
<code><span><?php </span><span><span>function</span><span>recurDir</span><span>(<span>$pathName</span>)</span> {</span><span>//将结果保存在result变量中</span><span>$result</span> = <span>array</span>(); <span>$temp</span> = <span>array</span>(); <span>//判断传入的变量是否是目录</span><span>if</span>(!is_dir(<span>$pathName</span>) || !is_readable(<span>$pathName</span>)) { <span>return</span><span>null</span>; } <span>//取出目录中的文件和子目录名,使用scandir函数</span><span>$allFiles</span> = scandir(<span>$pathName</span>); <span>//遍历他们</span><span>foreach</span>(<span>$allFiles</span><span>as</span><span>$fileName</span>) { <span>//判断是否是.和..因为这两个东西神马也不是。。。</span><span>if</span>(in_array(<span>$fileName</span>, <span>array</span>(<span>'.'</span>, <span>'..'</span>))) { <span>continue</span>; } <span>//路径加文件名</span><span>$fullName</span> = <span>$pathName</span>.<span>'/'</span>.<span>$fileName</span>; <span>//如果是目录的话就继续遍历这个目录</span><span>if</span>(is_dir(<span>$fullName</span>)) { <span>//将这个目录中的文件信息存入到数组中</span><span>$result</span>[<span>$fullName</span>] = recurDir(<span>$fullName</span>); }<span>else</span> { <span>//如果是文件就先存入临时变量</span><span>$temp</span>[] = <span>$fullName</span>; } } <span>//取出文件</span><span>if</span>(<span>$temp</span>) { <span>foreach</span>(<span>$temp</span><span>as</span><span>$f</span>) { <span>$result</span>[] = <span>$f</span>; } } <span>return</span><span>$result</span>; } <span>//验证一下这个函数是否好用!</span><span>$tree</span> = recurDir(<span>'cart_ajax'</span>); <span>echo</span><span>"<pre class="brush:php;toolbar:false">"
cart_ajax資料夾結構
js文件夾下的內容
大功告成了!目錄的等級確實是這樣的,不過看起來也太low了吧!稍微美化一下吧!
<code><span><span>function</span><span>beautifulTree</span><span>(<span>$arr</span>, <span>$l</span> = <span>'-|'</span>)</span> {</span><span>static</span><span>$l</span> = <span>''</span>; <span>static</span><span>$str</span> = <span>''</span>; <span>//遍历刚才得到的目录树</span><span>foreach</span>(<span>$arr</span><span>as</span><span>$key</span>=><span>$val</span>) { <span>//如果是个数组,也就代表它是个目录,那么就在它的子文件中加入-|来表示是下一级吧</span><span>if</span>(is_array(<span>$arr</span>[<span>$key</span>])) { <span>$str</span>.=<span>$l</span>.<span>$key</span>.<span>"<br>"</span>; <span>$l</span>.=<span>'-|'</span>; beautifulTree(<span>$arr</span>[<span>$key</span>], <span>$l</span>); }<span>else</span> { <span>$str</span>.=<span>$l</span>.<span>$val</span>.<span>"<br>"</span>; } } <span>$l</span> = <span>''</span>; <span>return</span><span>$str</span>; } <span>$beautifulTree</span> = beautifulTree(<span>$tree</span>); <span>echo</span><span>"<pre class="brush:php;toolbar:false">"
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i
').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介紹了PHP讀取目錄樹,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。