0

I have a 2D array in php which holds the date:

$cal[$year][$month] = $event; 

Output of the array is:

Array ( [2012] => Array ( [6] => 10.92 [11] => 16.38 [8] => 1.3 [9] => 16.96 ) 

I would like to sort the array by year and month. How do I do this?

Thank you!

3
  • have u tried sort() functions? Commented Sep 12, 2012 at 15:55
  • check this, php.net/manual/en/function.array-multisort.php Commented Sep 12, 2012 at 15:57
  • take a look at the array_multisort function Commented Sep 12, 2012 at 16:02

2 Answers 2

1

you should look to the array_multisort function, you can find informations here: http://php.net/manual/en/function.array-multisort.php

the second example is what you are looking for

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

Comments

0

According to your following array:

$cal[$year][$month] = $event;

and taking into account that $year and $month are both numeric (if not, just cast them).

For ordering both years and months in ASCENDING order, do:

ksort($cal); //sort years
foreach($cal as &$arr) {
   ksort($arr); //sort months
}

if you want it in DESCENDING order, do:

krsort($cal); //sort years
foreach($cal as &$arr) {
   krsort($arr); //sort months
}

you can interchange ksort() and krsort() in both examples if you want a mix sort, like years ASCENDING and months DESCENDING.

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.