search
HomeBackend DevelopmentPHP ProblemPHP traverses TXT files in a directory and sorts them by time

PHP traverses TXT files in a directory and sorts them by time

Dec 05, 2019 am 09:39 AM
phptxtsorttimeTraverse

PHP traverses TXT files in a directory and sorts them by time

Traverse txt files in the directory

Example:

//遍历目录下文件方法
function printdir($dir)
{
	$files = array();
	//opendir() 打开目录句柄
	if($handle = @opendir($dir)){
	//readdir()从目录句柄中(resource,之前由opendir()打开)读取条目,
	// 如果没有则返回false
		while(($file = readdir($handle)) !== false){//读取条目
			if( $file != ".." && $file != "."){//排除根目录
				if(is_dir($dir . "/" . $file)) {//如果file 是目录,则递归
					$files[$file] = printdir($dir . "/" . $file);
				} else {
					//获取文件修改日期
					$filetime = date('Y-m-d H:i:s', filemtime($dir . "/" . $file));
					//文件修改时间作为健值
					$files[$filetime] = $file;
				}
			}
		}
		@closedir($handle);
		return $files;
	}
}

Online video tutorial recommendation:php video tutorial

Sort by time based on the returned array

Example:

 //根据修改时间对数组排序
function arraysort($aa) {
	if( is_array($aa)){
		ksort($aa);
		foreach($aa as $key => $value) {
			if (is_array($value)) {
				$arr[$key] = arraysort($value);
			} else {
				$arr[$key] = $value;
			}
		}
		return $arr;
	} else {
		return $aa;
	}
}

$dir = "/php";
//输出 /php 下所有文件
print_r(arraysort(printdir($dir)));

Related article tutorial recommendations:php tutorial

The above is the detailed content of PHP traverses TXT files in a directory and sorts them by time. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.