rameezmeans
rameezmeans

Reputation: 850

PHP- years and months array keys and inside values sort

Here is an php array representing years and months:

array:3 [
  2017 => array:2 [
    0 => "2"
    1 => "3"
  ]
  2018 => array:2 [
    0 => "1"
    1 => "5"
  ]
  2019 => array:3 [
    0 => "10"
    1 => "12"
    2 => "6"
  ]
]

I want to sort it on the basis of key (descending) on first level and values (descending) on the second level. by this records of latest month in latest year will appear. So the output must be:

array:3 [
  2019 => array:3 [
      0 => "12"
      1 => "10"
      2 => "6"
    ]
  2018 => array:2 [
      0 => "5"
      1 => "1"
  ]
  2017 => array:2 [
    0 => "3"
    1 => "2"
  ]
]

Upvotes: 0

Views: 121

Answers (1)

Nick
Nick

Reputation: 147146

This is just a question of applying krsort to the top-level of the array and rsort to each sub-level:

krsort($array);
array_walk($array, function (&$v) { rsort($v); });

Output:

Array
(
    [2019] => Array
        (
            [0] => 12
            [1] => 10
            [2] => 6
        )
    [2018] => Array
        (
            [0] => 5
            [1] => 1
        )
    [2017] => Array
        (
            [0] => 3
            [1] => 2
        )
)

Demo on 3v4l.org

Upvotes: 2

Related Questions