duandun3178 2014-11-21 12:07
浏览 34
已采纳

Sort()返回一个乱序数组

I have an array that is populated from the function iterator_to_array. After I sort it (tried asort(), ksort() and rsort() and all of them show the same result: an out of order array...

This is my code.

$fi = new FilesystemIterator($location, FilesystemIterator::SKIP_DOTS);
$file_paths = iterator_to_array( $fi, false);
rsort($file_paths);
echo "<pre>", print_r($file_paths), "</pre>";

The print_r returns:

Array
(
[0] => SplFileInfo Object
    (
        [pathName:SplFileInfo:private] => /opt/lampp/htdocs/majo/log_files/teste/log2014324.txt
        [fileName:SplFileInfo:private] => log2014324.txt
    )

[1] => SplFileInfo Object
    (
        [pathName:SplFileInfo:private] => /opt/lampp/htdocs/majo/log_files/teste/log2014325.txt
        [fileName:SplFileInfo:private] => log2014325.txt
    )

[2] => SplFileInfo Object
    (
        [pathName:SplFileInfo:private] => /opt/lampp/htdocs/majo/log_files/teste/log2014323.txt
        [fileName:SplFileInfo:private] => log2014323.txt
    )

[3] => SplFileInfo Object
    (
        [pathName:SplFileInfo:private] => /opt/lampp/htdocs/majo/log_files/teste/log2014322.txt
        [fileName:SplFileInfo:private] => log2014322.txt
    )

)

After a routine to clear the name of the file I get this output:

2014324.txt
2014325.txt
2014323.txt
2014322.txt

However because of rsort() (the function used at that time) it should be:

2014325.txt
2014324.txt
2014323.txt
2014322.txt

Everytime the 2014325.txt is out of place and I can't seem to get it in place, does anyone know how to fix this?

I can implement a solution that involves doing the sorting in a manual way, but it will spend a lot more time and resources, however.

PS: ksort() output:

2014322.txt
2014323.txt
2014325.txt
2014324.txt
  • 写回答

3条回答 默认 最新

  • dounai7148 2014-11-21 12:21
    关注

    iterator_to_array gives you an array of objects, but php has no clue how to compare them. You have to extract the sort key (e.g. a path) and tell php to sort by this key, for example:

    $fi = new FilesystemIterator($location, FilesystemIterator::SKIP_DOTS);
    $file_paths = array();
    foreach($fi as $f)
        $file_paths[$f->getRealPath()] = $f;
    ksort($file_paths);
    

    If you only need file paths and not interested in additional data SplFileInfo provides, then glob might be a simpler option:

    $file_paths = glob("$location/*");
    

    Note that the glob output is already sorted.

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?