-2

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

my array looks like the following:

$myArray =
    ['[email protected]'] =>
        ['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'
    ['[email protected]'] =>
        ['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.

3
  • Definitely a duplicate. But this specific issue is usort() requires a custom sorting method. It doesn't sort anything by itself. php.net/manual/en/function.usort.php Commented Jul 10, 2017 at 20:09
  • 2
    krsort should work as long as your dates are Y-m-d format. Commented Jul 10, 2017 at 20:09
  • what is the source of this data? Where do you get it from? a database? Commented Jul 10, 2017 at 20:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@JayBlanchard, you're totally right. my bad. will update accordingly.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.