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.

1

2 Answers 2

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.

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

3 Comments

I used an anonymous function, which needs php 5.3+. See the example in the manual for other ways to specify the comparison function.
yep, works after I separated the function and called it by usort($response['items'], 'function_name');, thanks!
...well this changes everything...
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.