douqiang7976 2016-02-24 12:29
浏览 32
已采纳

PHP glob(*)和foreach的最大数字basename

I have this files path/0.php path/3.php path/2.php path/7.php

I want to display the files with foreach and I use this code:

$files = glob("system/$var/$var/$var/*/*.php");
foreach($files as $file) {
    //code here per $file.
    //for example:
    $basename = basename($file);
    echo str_replace(".php",null,$basename) . "<br>";
    include $file; //heres i need the path of the files.
}

But I want to sort this files by the largest number that is before the .php extension, like this:

Array
(
    [0] => path/7.php
    [1] => path/3.php
    [2] => path/2.php
    [3] => path/0.php
)

so?

update, rsort is not good for me, because the is a path/to/file, before the numbers, i want to use the path of the files.

  • 写回答

4条回答 默认 最新

  • duanshan7261 2016-02-24 14:26
    关注

    You can sort the array being returned using usort:

    $files = glob("system/$var/$var/$var/*/*.php"
    usort($files, function ($b, $a) {
        return strcmp( substr($a, strrpos($a, '/') + 1), 
                       substr($b, strrpos($b, '/') + 1) ); 
    });
    

    Note that this will use string comparison, so 10.php will end up between 1.php and 2.php. If that's not what you want you have to use numeric comparison. i.e. using PHP 7's "spaceship" operator:

    $files = glob("system/$var/$var/$var/*/*.php"
    usort($files, function ($b, $a) {
        return ((int)substr($a, strrpos($a, '/') + 1)) 
           <=> ((int)substr($b, strrpos($b, '/') + 1)); 
    });
    

    Edit: I swapped $a and $b in the callback signatures to reverse the sorting order

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器