Search code examples
phparrayssortingmultidimensional-array

Sort 1st level of a multidimensional array based on a nested associative key within each row


Thought I will point out first that I have looked around on Stackoverflow and the internet already and although they are plenty of examples none of them are explained into such a way for me to understand how to convert the code to work with my array structure.

I believe I need to use one of the functions uksort or uasort but unsure on this as well.

My array looks like the following.

Array
(
    [0] => Array
        (
            [Result] => Array
                (
                    [id] => 260
                    [event_id] => 72
                    [year] => 2010
                    [york_score] => 27
                    [york_points] => 0.0
                    [lancs_score] => 51
                    [lancs_points] => 4.0
                    [winner] => L
                    [confirmed] => Y
                    [updated] => 2010-05-01 16:10:03
                )

            [Event] => Array
                (
                    [id] => 72
                    [sport_id] => 25
                    [event_title] => 1st Team
                    [Sport] => Array
                        (
                            [id] => 25
                            [sport_title] => Netball
                        )

                )

        )

And where its [0] means it continues on.

I need to sort all of the arrays [0,1,2,3,...] by the sport_title key found in [Event][Sport]

Does anyone know how to create a sorting function to do this?

Some explanation of how the function is working would also be helpful if I later need to adapter/alter the code to work else where on my site.


Solution

  • Where $array is the name of the array which holds the array you posted in your question.

    function sort_multi($item_1, $item_2)
    {
       // strcmp looks at two strings and, based off the characters' and their order,
       // determines which one is numerically greater. When this function returns a
       // negative, for example, it means the first item it's comparing is less that the
       // second item (ef and eg, for example). The usort function then rearranges
       // the array based off these comparisons.
       return strcmp($item_1['Event']['Sport']['sport_title'], $item_2['Event']['Sport']['sport_title']);
    }
    
    usort($array, 'sort_multi');