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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题