dp610807 2012-03-19 19:57
浏览 123
已采纳

PHP:使用-1-和-10-等值对数组进行排序

I have a function that gets filenames from a directory, and then puts them in an array. All the filenames start with a code, as an example: -0-filename.php, -1-filename.php, -2-filename.php and -10-filename.php.

After some steps, the filenames are echoed out. The process looks like this:

rsort( $archiveArray );
$amount = count( $archiveArray );
$i = 0;
while( $i <= $amount )
{
    echo $archiveArray[$i];
    $i++;
}

Anyways. The problem is; when I get 10 files in the directory, and try to do the echoing process above, I get the names in a wrong order. - It's supposed to be :

-10-filename.php

-9-filename.php

-8-filename.php

...

-1-filename.php

-0-filename.php

But instead, I get

-9-filename.php

-8-filename.php

...

-10-filename.php

-1-filename.php

-0-filename.php

What's the quickest and easiest way to fix this?

EDIT:

If it wasn't obvious, the filenames are not always identical, even when not including the codes. The are always in this format: -number-randomtext.php, where number is always one higher than the last one, and randomtext can really be anything.

  • 写回答

5条回答 默认 最新

  • dongyi1215 2012-03-19 20:10
    关注

    Using rsort with SORT_NATURAL works if you're running PHP 5.4. If you're not, however:

    natsort( $archiveArray );
    $archiveArray = array_reverse( $archiveArray );
    

    ...will do the same thing. Just use natsort to do the natural order sorting, then reverse the array.

    Test code (PHP 5.3.3):

    php > $array = array( '-1-blah', '-2-foo', '-12-boo', '-11-yaay', '-3-bar' );
    php > natsort( $array );
    php > print_r( $array );
    Array
    (
        [0] => -1-blah
        [1] => -2-foo
        [4] => -3-bar
        [3] => -11-yaay
        [2] => -12-boo
    )
    php > $array = array_reverse( $array );
    php > print_r( $array );
    Array
    (
        [0] => -12-boo
        [1] => -11-yaay
        [2] => -3-bar
        [3] => -2-foo
        [4] => -1-blah
    )
    php > 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序