forbidden
forbidden

Reputation: 81

How to sort a multidimensional array by alphanumeric value?

I have an array like this below,

Array
(
    [2] => Array
        (
            [id] => 75
            [program] => Apr 2020-Nov 2020
        )

    [1] => Array
        (
            [id] => 73
            [program] => Feb 2016-Aug 2020
        )

    [0] => Array
        (
            [id] => 72
            [program] => May 2020-Dec 2020
        )

)

The resultant array should be

Array
(


    [1] => Array
        (
            [id] => 73
            [current_program] => Feb 2016-Aug 2020
        )
    [2] => Array
        (
            [id] => 75
            [current_program] => Apr 2020-Nov 2020
        )

    [0] => Array
        (
            [id] => 72
            [current_program] => May 2020-Dec 2020
        )

)

It should sort based on the year. I have tried to achieve by "strnatcasecmp", but the array is sorting by alphabet not by the numeric value in it

    usort($programp, function($a, $b) {
        return strnatcasecmp($a['program'], $b['program']);
    });

Any help would be appreciated!

Thanks

Upvotes: 1

Views: 154

Answers (2)

bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

//Sort indexes so the keys are 0,1,2 instead of 1,2,0
//This is important when sorting down below with asort()
$arr = array_values($arr); 

//Go through every "program" (dateinterval in your array)
//and make a new array in the format year-monthnr
//Date parse returns the number of jan(1),feb(2),mar(3) etc..
$year_month = [];
foreach(array_column($arr,'program') as $key => $item) {       
    $year = explode(' ', explode('-',$item)[0])[1];
    $month = date_parse(explode(' ', explode('-',$item)[0])[0])['month'];
    $year_month[] = $year . '-' . $month;
}

//Sort with mainted indexes (keys)
asort($year_month); 

//Create new array "mapped" keys to the original array $arr
$new_arr = [];
foreach($year_month as $key=>$item) {
    $new_arr[] = $arr[$key];
}

Output of $new_arr would be:

Array
(
    [0] => Array
        (
            [id] => 73
            [program] => Feb 2016-Aug 2020
        )

    [1] => Array
        (
            [id] => 75
            [program] => Apr 2020-Nov 2020
        )

    [2] => Array
        (
            [id] => 72
            [program] => May 2020-Dec 2020
        )

)

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

You need to convert the first month and year into a timestamp, sort that thereby sorting the original:

foreach($programp as $values) {
    $starts[] = strtotime(explode('-', $values['program'])[0]);
} 
array_multisort($starts, $programp);

Before sorting the $starts array would look like this, easy to sort:

Array
(
    [0] => 1585692000
    [1] => 1454281200
    [2] => 1588284000
)

You probably want some error checking to make sure $values['program'] is not empty etc...

Upvotes: 1

Related Questions