Dadou
Dadou

Reputation: 1008

php sort multimentional array with numeric keys

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.

Upvotes: 1

Views: 422

Answers (2)

Sahil Gulati
Sahil Gulati

Reputation: 15141

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);

Upvotes: 2

ishegg
ishegg

Reputation: 9927

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

Upvotes: 3

Related Questions