-2

i have seen several SO answers but none seem to address this very simple situation.

my array looks like the following:

$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'

within each of the first levels (email address), how would I sort the second level (date yyyy-mm-dd) in descending?

I did try this:

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

and I also tried to ksort with a function as well with no success.

thank you very much.

edwardsmarkf
  • 1,387
  • 2
  • 16
  • 31
  • Definitely a duplicate. But this specific issue is `usort()` requires a custom sorting method. It doesn't sort anything by itself. http://php.net/manual/en/function.usort.php – rideron89 Jul 10 '17 at 20:09
  • 2
    [krsort](https://php.net/krsort) should work as long as your dates are `Y-m-d` format. – Jonathan Kuhn Jul 10 '17 at 20:09
  • what is the source of this data? Where do you get it from? a database? – Ivo P Jul 10 '17 at 20:15

1 Answers1

3

Use this:

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

or (but i prefer the first option)

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

This is the sorting method:

krsort — Sort an array by key in reverse order

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

See a working example here: https://3v4l.org/pok2e

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
  • Do or do not, there is no "try". A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Jul 10 '17 at 20:16
  • @JayBlanchard, you're totally right. my bad. will update accordingly. – Alex Tartan Jul 10 '17 at 20:17
  • thank you alex - the brain had disengaged when i posted this silly question. when you try to jump back and forth between node & php, you forget stuff. – edwardsmarkf Jul 11 '17 at 01:28