Reputation: 193
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.
Upvotes: 3
Views: 376
Reputation: 65274
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);
Upvotes: 0
Reputation: 31813
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.
Upvotes: 9