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 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题