3

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.

Ryan Koehler
  • 193
  • 1
  • 8

2 Answers2

9
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.

goat
  • 31,486
  • 7
  • 73
  • 96
0

AFAIK there is no direct way to to that. I typically do something like

$items=array();
foreach($mainarray['items'] as $k=>$v) $items[$v['end']['$dateTime'."-$k"]]=$v;
ksort($items);
$mainarray['items']=array_values($items);
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92