开发者

newbie: php how to read in file names in order of filename

I want to "include" the last 2 files in my php file based on their names.

So the names are:

01-blahbla.php
02-sdfsdff.php
03-aaaaaaa.php
04-bbbbbbb.php
05-wwwwwwi.php

and I only want to include 05 and 04 since their name starts with the biggest number.

How do I go on a开发者_运维技巧bout doing this?


Assuming there is only the numbered files in the folder, you could use

$files = glob('/path/to/files/*.php'); // get all php files in path
natsort($files);                       // sort in natural ascending order
$highest = array_pop($files);          // get last file, e.g. highest number
$second  = array_pop($files);          // again for second highest number


Put the values in an array, reverse sort it using rsort() and then take the first two:

$values = array('01-blahbla.php', '02-sdfsdff.php', '03-aaaaaaa.php', '04-bbbbbbb.php', '05-wwwwwwi.php');
rsort($values);
$file1 = $values[0];
$file2 = $values[1];
require_once $file1;
require_once $file2;

The PHP manual at php.net has some great info for the various sort methods.

Update:

As Psytronic noted, rsort will not work for numbers, but you can create a custom function that easily does the same thing:

function rnatsort(&$values) {
  natsort($values);
  return array_reverse($values, true);
}
$files = rnatsort($values);


List the directory contents into an array. Sort that array using built-in PHP sorting functions. Do a require_once() on the first two elements of the array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜