duancuan7057 2012-11-19 10:12
浏览 68

数组按索引变量排序

I'm having some difficulties sorting a simple array that looks like this:

Array
(
    [3] => Array
        (
            [0] => EU West (Ireland)
            [1] => eu-west-1
        )

    [7] => Array
        (
            [0] => South America (Sao paulo)
            [1] => sa-east-1
        )

    [0] => Array
        (
            [0] => US East (Virginia)
            [1] => us-east-1
        )

    [4] => Array
        (
            [0] => Asia Pasific (Tokyo)
            [1] => ap-northeast-1
        )

    [2] => Array
        (
            [0] => US West (Oregon)
            [1] => us-west-2
        )

    [1] => Array
        (
            [0] => US West (N. California)
            [1] => us-west-1
        )

    [5] => Array
        (
            [0] => Asia Pasific (Singapore)
            [1] => ap-southeast-1
        )

    [6] => Array
        (
            [0] => Asia Pasific (Sydney)
            [1] => ap-southeast-2
        )

)

I want to sort this array on Index. I used ksort() but it doesn't work, it leaves an output 1.

  • 写回答

3条回答 默认 最新

  • dqpciw9742 2012-11-19 10:14
    关注

    ksort() doesn't return the sorted array, but rather it sorts the array in place. After calling ksort($array), the contents of $array will be sorted. The function returns whether the sort was successful or not.

    Example:

    $array = array(1 => 1, 20 => 1, 5 => 1);
    
    echo "Before ksort():
    ";
    print_r($array);
    
    if (ksort($array)) {
        echo "ksort() completed successfully.
    ";
    }
    
    echo "After ksort():
    ";
    print_r($array);
    

    The above prints:

    Before ksort():
    Array
    (
        [1] => 1
        [20] => 1
        [5] => 1
    )
    ksort() completed successfully.
    After ksort():
    Array
    (
        [1] => 1
        [5] => 1
        [20] => 1
    )
    

    You shouldn't check the return value of ksort() though, since ksort() can only fail in situations in which it doesn't even get to return a failure. Therefore, the function will either return true or the script will die, in which case the return value is irrelevant (it will always be true).

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程