views:

36

answers:

3

Is there away i can sort the following array into the correct order?

Array
(
    [0] => apr
    [1] => aug
    [2] => dec
    [3] => feb
    [4] => jan
    [5] => jul
    [6] => jun
    [7] => mar
    [8] => may
    [9] => nov
    [10] => oct
    [11] => sep
)

NOTE The array comes to me like this, and sometimes it will not have all the months.

Obviously I want in chronological order.

Thanks

+1  A: 

Use usort along with a custom comparator that you define. The custom comparator will work with the date format your code deals with and return an integer greater than, less than or equal to zero depending on how the two dates passed to it compare.

Hippo
+4  A: 
function sort_months($item_1, $item_2)
{
    $item_1 = strtotime('1 ' . $item_1 . ' 2000');
    $item_2 = strtotime('1 ' . $item_2 . ' 2000');
    if($item_1 == $item_2)
    {
        return 0;
    }
    return $item_1 > $item_2 ? 1 : -1;
}

$arr = array
(
    'apr',
    'aug',
    'dec',
    'feb',
    'jan',
    'jul',
    'jun',
    'mar',
    'may',
    'nov',
    'oct',
    'sep'
);

usort($arr, 'sort_months');
Tim Cooper
+1  A: 

To mantain index association and any other string values, try the code bellow:

function find_position($needle,  $haystack) {

    // put here the elements in order
    //$defined_order = array('jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez');
    $defined_order = array('jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec');

    $needle_order = -1;
    foreach($defined_order as $pos => $item) {
        if($needle == $item) {
            $needle_order = $pos;
            break;
        }
    }

    return($needle_order);
}

function order_array($unsorted_arr) {

    $key_orders = array();
    $not_available = array();
    foreach($unsorted_arr as $key => $val) {
        if($position = find_position($val, $unsorted_arr)) {
            $key_orders[$key] = $position;
        } else {
            $not_available[$key] = $val;
        }
    }

    asort($key_orders);

    $ordered = array();
    foreach($key_orders as $key => $posit) {
        $ordered[$key] = $unsorted_arr[$key];
    }

    return($ordered);
    // OR 
    // return(array('ordered'=>$ordered, 'not_available'=>$not_available));
}


$unsorted = array(0 => 'apr', 1 => 'aug', 2 => 'dec', 3 => 'feb', 4 => 'jan', 5 => 'jul', 6 => 'jun', 7 => 'mar', 8 => 'may', 9 => 'nov', 10 => 'oct', 11 => 'sep' );

$sorted = order_array($unsorted);
Resegue