PHP遞歸創(chuàng)建多級目錄,php遞歸
Jun 13, 2016 am 08:51 AMPHP遞歸創(chuàng)建多級目錄,php遞歸
我的第一個感覺就是用遞歸創(chuàng)建,具體思路如下:
function Directory($dir){ if(is_dir($dir) || @mkdir($dir,0777)){ //查看目錄是否已經(jīng)存在或嘗試創(chuàng)建,加一個@抑制符號是因?yàn)榈谝淮蝿?chuàng)建失敗,會報一個“父目錄不存在”的警告。 echo $dir."創(chuàng)建成功<br>"; //輸出創(chuàng)建成功的目錄 }else{ $dirArr=explode('/',$dir); //當(dāng)子目錄沒創(chuàng)建成功時,試圖創(chuàng)建父目錄,用explode()函數(shù)以'/'分隔符切割成一個數(shù)組 array_pop($dirArr); //將數(shù)組中的最后一項(xiàng)(即子目錄)彈出來, $newDir=implode('/',$dirArr); //重新組合成一個文件夾字符串 Directory($newDir); //試圖創(chuàng)建父目錄 if(@mkdir($dir,0777)){ echo $dir."創(chuàng)建成功<br>"; } //再次試圖創(chuàng)建子目錄,成功輸出目錄名 } } Directory("A/B/C/D/E/F");
輸出結(jié)果如圖:
但是可以看得出來,寫得也太麻煩了,在手冊里翻看文件函數(shù),看到一個dirname()函數(shù),其原型如下:
string dirname ( string $path )
給出一個包含有指向一個文件的全路徑的字符串,本函數(shù)返回去掉文件名后的目錄名。
在 Windows 中,斜線(/)和反斜線(\)都可以用作目錄分隔符。在其它環(huán)境下是斜線(/)。
可以稍稍地優(yōu)化一下:
function Directory($dir){ if(is_dir($dir) || @mkdir($dir,0777)){ echo $dir."創(chuàng)建成功<br>"; }else{ Directory(dirname($dir)); if(@mkdir($dir,0777)){ echo $dir."創(chuàng)建成功<br>"; } } }
效果一樣。
之后我在在網(wǎng)上搜一下答案,找到一個異常精辟的:
function Directory( $dir ){ return is_dir ( $dir ) or Directory(dirname( $dir )) and mkdir ( $dir , 0777); }
現(xiàn)在來解釋一下整個函數(shù):
先介紹一下PHP中邏輯運(yùn)算符的優(yōu)先級順序:&& > || > and > or,即符號型>字母型,AND型>OR型,所以函數(shù)體可以看成:
is_dir ( $dir )? or? (Directory(dirname( $dir ))? and?? mkdir ( $dir , 0777));
先判斷目標(biāo)目錄是否存在,若存在,依or的短路特性,后面的整體被短路,跳過執(zhí)行;若目標(biāo)目錄不存在,則執(zhí)行后面的函數(shù)體:
Directory(dirname( $dir ))? and?? mkdir ( $dir , 0777)
我考慮了一下先進(jìn)行遞歸的用意:先執(zhí)行遞歸,意在確認(rèn)其父目錄(dirname($dir))都已經(jīng)創(chuàng)建完畢,使后面的mkdir()函數(shù)不會創(chuàng)建子目錄時找不到父目錄發(fā)出警告。
進(jìn)入遞歸深處后,確認(rèn)最深處的根目錄存在后,從根目錄向下依次創(chuàng)建目錄。
最后,建議要找工作的親們,去網(wǎng)上找些大公司面試題做一下,畢竟他們考得較為綜合較深,在學(xué)習(xí)知識的時候,也刷一下題,另外也一定要做一下,因?yàn)楹苋菀籽鄹呤值?,一開始的函數(shù),我優(yōu)化了好幾遍才能正常使用。
這就是一道PHP遞歸創(chuàng)建多級目錄面試題目,以后小編會再找些有意思的面試題跟大家分享。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The "undefinedindex" error occurs because a key that does not exist in the array is accessed. Solutions include: 1. Use isset() to check whether the key exists, which is suitable for processing user input; 2. Use array_key_exists() to determine whether the key is set, and it can be recognized even if the value is null; 3. Use the empty merge operator?? to set the default value to avoid directly accessing undefined keys; in addition, you need to pay attention to common problems such as the spelling of form field names, the database result is empty, the array unpacking is not verified, the child keys are not checked in foreach, and the session_start() is not called.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.
