duanbage2161 2015-05-30 09:38
浏览 41
已采纳

排序多维数组 - 保持键的值

I want to sort my array based on the key (which is a date) - preferrably both ASC and DESC.

I have tried to use several of the methods on SO, but keep getting bad results - so I thought I would ask the question again.

I have this array:

Array
(
    [2015-05-29] => Array
        (
            [a] => 13
            [b] => 1
            [c] => 12
        )

    [2015-05-28] => Array
        (
            [a] => 10
            [b] => 1
            [c] => 1
        )

    [2015-05-27] => Array
        (
            [a] => 2
        )

    [2015-05-30] => Array
        (
            [b] => 24
            [c] => 25
        )

)

I use this function - which should work according to several posts:

uasort($days, function($a, $b) {
    return $a['points'] - $b['points'];
}); 

But it doesn't, as the array gets returned like this:

    Array
    (
        [2015-05-30] => Array
            (
                [b] => 24
                [c] => 25
            )

        [2015-05-27] => Array
            (
                [a] => 2
            )

        [2015-05-28] => Array
            (
                [a] => 10
                [b] => 1
                [c] => 1
            )

        [2015-05-29] => Array
            (
                [a] => 13
                [b] => 1
                [c] => 12
            )

    )

I want to have the array returned like this:

   Array
(
    [2015-05-27] => Array
        (
            [a] => 2
        )

    [2015-05-28] => Array
        (
            [a] => 10
            [b] => 1
            [c] => 1
        )

    [2015-05-29] => Array
        (
            [a] => 13
            [b] => 1
            [c] => 12
        )

    [2015-05-30] => Array
        (
            [b] => 24
            [c] => 25
        )

)

or in reverse order!

Who can help me solve this problem?

  • 写回答

1条回答 默认 最新

  • doumi9661 2015-05-30 09:45
    关注

    You don't need any own sorting function. Just use ksort()/krsort(), .e.g.

    //ASC         //DESC
    ksort($arr);  //krsort($arr);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动
  • ¥15 大一C语言期末考试,求帮助🙏🙏
  • ¥15 ch340驱动未分配COM
  • ¥15 Converting circular structure to JSON
  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader
  • ¥45 谷歌浏览器出现开发者工具无法显示已创建的,但您可以调试已部署的代码。 状态代码 404, net::ERR HTTP RESPONSE CODE FAILURE
  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错