SCC
SCC

Reputation: 87

Access files in a directory and write the file paths to a text file in ascending order using PHP

I have a list of video files in my server. I would like to list out all the video files in this directory and write it to a text file. These video files are all having the same name output-x.mp4, and x is the number from 0 to an unknown figure. The total number of video files is dynamic and therefore I don't get to know the number of the last video. I have the below code to access all the video files in this directory. It works fine with only one problem: The video files written to the text file are not sorted in ascending order.

$directory = "video/myvideo";
$fp = fopen($_SERVER['DOCUMENT_ROOT']."Path/to/text/file", "wb");
$split_video_files = scandir($directory);
foreach($split_video_files as $file)
{
    $content = "file ".$directory.$file."\r\n";
    fwrite($fp, $content);
}
fclose($fp);

What the text file gave me is this:

video/myvideo/output-0.mp4
video/myvideo/output-1.mp4
video/myvideo/output-10.mp4
video/myvideo/output-11.mp4
video/myvideo/output-12.mp4
video/myvideo/output-13.mp4
video/myvideo/output-14.mp4
video/myvideo/output-2.mp4
video/myvideo/output-3.mp4
video/myvideo/output-4.mp4
video/myvideo/output-5.mp4
video/myvideo/output-6.mp4
video/myvideo/output-7.mp4
video/myvideo/output-8.mp4
video/myvideo/output-9.mp4

It lists out all the filename that start with "1" first before proceed to "2" and so on. Any ways for me to sort it in ascending order so that it starts from 0, 1, 2,…?

Upvotes: 0

Views: 50

Answers (1)

Class
Class

Reputation: 3160

Try using the natsort array sorting function DEMO

natsort($split_video_files);

Upvotes: 1

Related Questions