1

I'm making an event calendar. Everything needs to be sorted chronologically.

This is the array I'm currently sorting:

$years = array(
    2018 => array(
        01 => array(),
        02 => array()
    ),
    2017 => array(,
        02 => array()
        01 => array()
    )
);

I originally have a larger array used to populate this $years.

Using ksort, I've sorted my years correctly, i.e. they are in chronological order. However, I can't sort my third level (see in 2017, my array is 02,01 whereas it should read 01,02). The last level or the array (such as 2017 > 02) is sorted correctly, this is not an issue, as these are sorted by content within each of them.

I've tried array_multisort, ksort, usort and simply sort but none allow me to sort my keys as they are numeric.

0

2 Answers 2

3

How about iterating through the children elements, sorting them with ksort() as well:

<?php
$years = array(
    2018 => array(
        01 => array(),
        02 => array()
    ),
    2017 => array(
        02 => array(),
        01 => array()
    )
);
ksort($years);
foreach ($years as &$year) {
    ksort($year);
}
var_dump($years);

Demo

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

3 Comments

Oh, okay, I see my issue here, the use of & before my $year solves it. It's a bit too quick to mark the answer as accepted. May I ask what the & character does in this scenario?
It's using the element as a reference. This means, it will modify the actual $year array instead of simply returning a modified copy. Read about this here
Glad I could help!
2

Hope this one will be helpful. Here we are using ksort for sorting array on the basis of keys.

Try this code snippet here

ksort($years);
$result=array_map(
  function($array)  {
       ksort($array);
       return $array;
  },
  $years);

2 Comments

Since this does solve the issue, I've upvoted. However, I have used ishegg's answer, therefore I will be marking that answer as the solution. Thanks for your input!
@Akintunde Oh Thanks, Good to here this.. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.