5

I'm having a problem. I have a multidimensional array, that looks like this:

Array ( [0] => 
              Array ( 
                    [0] => Testguy2's post. 
                    [1] => testguy2 
                    [2] => 2013-04-03 
              ) 

        [1] => Array ( 
                    [0] => Testguy's post. 
                    [1] => testguy 
                    [2] => 2013-04-07 
              ) 
);

I want to sort the posts from the newest date to the oldest date, so it looks like this:

Array ( [1] => Array ( 
                     [0] => Testguy's post. 
                     [1] => testguy 
                     [2] => 2013-04-07 
               ) 
        [0] => Array ( 
                     [0] => Testguy2's post. 
                     [1] => testguy2 
                     [2] => 2013-04-03
               ) 
);

How do I sort it?

4 Answers 4

6
function cmp($a, $b){

    $a = strtotime($a[2]);
    $b = strtotime($b[2]);

    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

usort($array, "cmp");

Or for >= PHP 7

usort($array, function($a, $b){
    return strtotime($a[2]) <=> strtotime($b[2]);
});
Sign up to request clarification or add additional context in comments.

Comments

4

You can do it using usort with a Closure :

usort($array, function($a, $b) {
    $a = strtotime($a[2]);
    $b = strtotime($b[2]);
    return (($a == $b) ? (0) : (($a > $b) ? (1) : (-1)));
});

Comments

2

I'm just stepping away from my desk for the day so I can't offer specifics. But here's a good place to get started that includes examples: array_multisort

Comments

0
$dates = array();       
foreach($a AS $val){
    $dates[] = strtotime($val[2]);
}
array_multisort($dates, SORT_ASC, $a);

1 Comment

It would be considered to be nice to add some explanation around your code.

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.