0

I'm trying to reorganize my array orderned by date.

For example this is my array:

Array(
      [0] => august 
      [1] => july 
      [2] => october 
      [3] => september
)

How can i reorganize it chronologically, so it would become this:

Array(
      [0] => july 
      [1] => august 
      [2] => september 
      [3] => october
)
João Rafael
  • 413
  • 4
  • 10

2 Answers2

1

Use date_parse to parse the month name and convert it to the corresponding number and then use ksort to sort them.

$myArray = array('august', 'july', 'october', 'september');
foreach($myArray as $value) {
    $m = date_parse($value);
    $output[$m['month']] = ucfirst($value);
}
ksort($output);
print_r($output);

Output:

Array
(
    [7] => July
    [8] => August
    [9] => September
    [10] => October
)

Source: #12424968

Demo!

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
1

This should work for any date that strtotime can parse

function cmp($a, $b) 
{
    $a_time = strtotime($a);
    $b_time = strtotime($b);
    if ($a_time == $b_time) {
        return 0;
    }
    return ($a_time < $b_time) ? -1 : 1;    
}


// Array to be sorted
$array = array('november', 'august', 'december', 'february');
print_r($array);

// Sort and print the resulting array
usort($array, 'cmp');
print_r($array);

Output:

Array
(
    [0] => november
    [1] => august
    [2] => december
    [3] => february
)
Array
(
    [0] => february
    [1] => august
    [2] => november
    [3] => december
)
Nils
  • 436
  • 2
  • 5