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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?