1

This is my array:

$ar = array( 
 'Jan-2016' => 1,
 'Feb-2016' => 2,
 'Mar-2016' => 3,  
 'Apr-2016' => 4,
 'May-2016' => 4,
 'Jun-2016' => 4,
 'Jul-2016' => 4,
 'Aug-2016' => 4,
 'Sep-2016' => 4,
 'Oct-2016' => 4,
 'Nov-2016' => 4,
 'Dec-2016' => 4,
 'Jan-2015' => 1,
 'Mar-2015' => 1);

I want to sort this array by month & year. I've tried below code:

ksort($ar);

But i can't get result as i expected.

I need result as below array:

$ar = array(
 'Jan-2015' => 1,
 'Mar-2015' => 1,
 'Jan-2016' => 1,
 'Feb-2016' => 2,
 'Mar-2016' => 3,  
 'Apr-2016' => 4,
 'May-2016' => 4,
 'Jun-2016' => 4,
 'Jul-2016' => 4,
 'Aug-2016' => 4,
 'Sep-2016' => 4,
 'Oct-2016' => 4,
 'Nov-2016' => 4,
 'Dec-2016' => 4);
3
  • uksort is your option Commented Jan 7, 2016 at 9:29
  • php.net/manual/en/function.uksort.php - Sort an array by keys using a user-defined comparison function. Commented Jan 7, 2016 at 9:29
  • Can u provide code this? Commented Jan 7, 2016 at 9:31

2 Answers 2

10

uksort is the right function to use :

uksort($ar, function($a1, $a2) {
        $time1 = strtotime($a1);
        $time2 = strtotime($a2);

        return $time1 - $time2;
    });

print_r($ar);
Sign up to request clarification or add additional context in comments.

2 Comments

return $time1 - $time2 is much simpler.
@u_mulder well doesn't change much, but you're right
0

Supplement: Sort Order

$sortOrder = true;  // ASC
$sortOrder = false; // DESC

uksort($array, function($a, $b) use($sortOrder) {
    $timeA = strtotime($a);
    $timeB = strtotime($b);

    return $sortOrder ? ($timeA - $timeB) : ($timeB - $timeA);
});

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.