1

I am trying to sort this array by season_number however I am not really sure which function to use as I assume I need a custom sort? Any ideas?

Array
(
    [0] => Array
        (
            [season_number] => 7
            [show_id] => 21
            [show_seasons_id] => 14
        )

    [1] => Array
        (
            [season_number] => 6
            [show_id] => 21
            [show_seasons_id] => 31
        )

    [2] => Array
        (
            [season_number] => 1
            [show_id] => 21
            [show_seasons_id] => 40
        )

    [3] => Array
        (
            [season_number] => 2
            [show_id] => 21
            [show_seasons_id] => 41
        )
)

2 Answers 2

1

You can use the usort function with the 'compare' function:

function compare_my_elements( $arr1, $arr2 ) {
   $s1=$arr1["season_number"];
   $s2=$arr2["season_number"];
   if( $s1 == $s2 ) return 0;
   return ( $s1 > $s2 ? 1 : -1 );
}

usort( $my_md_array, compare_my_elements );
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

foreach ($array as $key => $val) {
    $newArr[$key] = $val['season_number'];
}
array_multisort($newArr, SORT_ASC, $array);

where $array is the array that you printed out.

3 Comments

nice one... though the $link probably would have to become $val.
@xtofl ah, yes you are correct. Sorry this is a piece of frequent code that I use and I copied and pasted. I used to use usort like your example, however, I found that this way is a tiny bit faster. Let me know if you have different findings.
I didn't tune it. This one may be faster due to the 'keys' being extracted only once, while with the user-defined function, the key-extraction logic is needed for each compare operation in the sorting algorithm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.