Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting by value in a multidimensional array

This is a multidimensional array I got from Google Calendar for displaying events.

Array
(
[items] => Array
    (
        [0] => Array
            (
                [status] => confirmed
                [summary] => Let's go swimming!
                [start] => Array
                    (
                        [dateTime] => 2011-12-30T09:00:00-05:00
                    )

                [end] => Array
                    (
                        [dateTime] => 2011-12-30T10:00:00-05:00
                    )

            )

        [1] => Array
            (
                [status] => confirmed
                [summary] => red wine
                [start] => Array
                    (
                        [dateTime] => 2011-12-28T06:00:00-05:00
                    )

                [end] => Array
                    (
                        [dateTime] => 2011-12-28T07:00:00-05:00
                    )

            )

        [2] => Array
            (
                [status] => confirmed
                [summary] => Christmas
                [start] => Array
                    (
                        [dateTime] => 2011-12-28T09:30:00-05:00
                    )

                [end] => Array
                    (
                        [dateTime] => 2011-12-28T10:30:00-05:00
                    )

            )
     )
)

I want to use PHP to sort by end[datetime]. If anyone could give me some help I would really appreciate it. I was wondering how to do it.

like image 357
Ryan Koehler Avatar asked Feb 01 '26 22:02

Ryan Koehler


1 Answers

usort($array['items'], function($a, $b){
    if ($a['end']['dateTime'] === $b['end']['dateTime']) return 0;
    else return ($a['end']['dateTime']  > $b['end']['dateTime']) ? -1 : 1;
});

usort();

In this particular case you can compare the dates as strings and get the correct answer due to the format. In some other cases, you might need other methods, like converting to unix timestamp and comparing those.

like image 80
goat Avatar answered Feb 04 '26 11:02

goat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!