V
V
Vladislav2020-04-02 15:03:46
PHP
Vladislav, 2020-04-02 15:03:46

How to sort array under date as mY?

There are such arrays:

array(29) {
  ["03.2020"]=>
  array(4) {
    ["likes"]=>
    int(46003)
    ["comments"]=>
    int(2663)
    ["reposts"]=>
    int(2939)
    ["views"]=>
    int(3386015)
  }
  ["01.2020"]=>
  array(4) {
    ["likes"]=>
    int(8958)
    ["comments"]=>
    int(612)
    ["reposts"]=>
    int(404)
    ["views"]=>
    int(699785)
  }
  ["02.2020"]=>
  array(4) {
    ["likes"]=>
    int(63776)
    ["comments"]=>
    int(3298)
    ["reposts"]=>
    int(3218)
    ["views"]=>
    int(4411204)
  }
  ["01.2019"]=>
  array(4) {
    ["likes"]=>
    int(33402)
    ["comments"]=>
    int(2037)
    ["reposts"]=>
    int(1096)
    ["views"]=>
    int(1236658)
  }
  ["12.2019"]=>
  array(4) {
    ["likes"]=>
    int(47592)
    ["comments"]=>
    int(1846)
    ["reposts"]=>
    int(832)
    ["views"]=>
    int(1552732)
  }
}

Their key in the form is formed like this date('mY').
There may be identical years but different months and vice versa.
It is possible to sort them, first by year, then by month.
To be something like this:
01.2010
02.2010
01.2015
03.2015

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2020-04-02
@cr1gger

array_uksort() - Sorts an array by keys, using a custom key comparison function.
Write a function that determines the relationship between two dates in your format (less than, equal to, greater than) and use it in array_uksort.

V
Vitaly Artemyev, 2020-04-02
@Vitaly48

Buddy, even you are too smart with the code, hold on, it's better this way:

$array = [
  '03.2001' => [],
  '01.2000' => [],
  '01.2005' => [],
  '05.2020' => [],
  '01.2020' => [],
  '30.1998' => [],
  '03.2020' => [],
  '09.2020' => [],
  '04.1998' => [],
  '11.2005' => [],
];

uksort($array, function(string $a, string $b): int {
  return date_create_from_format('m.Y', $a) <=> date_create_from_format('m.Y', $b);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question