php按特定键排序多维数组

时间:2017-07-10 20:04:47

标签: php

我已经看到了几个SO答案,但似乎都没有解决这个非常简单的情况。

我的数组如下所示:

$myArray =
    ['person_1@gmail.com'] =>
        ['2017-01-05']   =>
               'this is line one'
               'this is line two'
        ['2016-05-05']    =>
               'this is another line'
               'and this is a fourth line'
        ['2017-07-10']    =>
               'more lines'
               'yet another line'
    ['person_2@gmail.com'] =>
        ['2015-01-01'] =>
               'line for person_2'

在每个第一级(电子邮件地址)中,我如何按降序排序第二级(日期yyyy-mm-dd)?

我试过这个:

foreach ( $myArray as $emailAddress => $emailAddressArrayOfDates ) {
    usort ( $myArray[$emailAddress] );
}

我也尝试使用函数ksort但没有成功。

非常感谢你。

1 个答案:

答案 0 :(得分:3)

使用此:

foreach($myArray as $emailAddressKey=>$datesArray){
    krsort($myArray[$emailAddressKey]);
}
print_r($myArray);

或(但我更喜欢第一种选择)

foreach($myArray as &$value){
    krsort($value);
    // this works only if $value is passed by reference. If it's not,
    // it will update $value, but not $myArray[$key] as $value is only
    // a local variable.
}
print_r($myArray);

这是排序方法:

  

krsort - 按相反顺序对数组进行排序

     

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

请参阅此处的工作示例:https://3v4l.org/pok2e