Ukor Ukor - 6 months ago 11
PHP Question

Multidimensional array sorting in php

One of my function return this array... Yes I have seen other examples here on SO but non where able to solve my problem.

array (size=4)
0 =>
array (size=2)
'refferrer' => string 'http://google.com/' (length=18)
'number_of_reffers' => string '15' (length=2)
1 =>
array (size=2)
'refferrer' => string 'https://facebook.com/' (length=21)
'number_of_reffers' => string '22' (length=2)
2 =>
array (size=2)
'refferrer' => string 'none' (length=4)
'number_of_reffers' => string '74' (length=2)
3 =>
array (size=2)
'refferrer' => string 'http://findy.com/' (length=17)
'number_of_reffers' => string '6' (length=1)


I will like to know how to sort this array in descending and asscending order using the

'number_of_reffers'...

What I am trying to say is that i want the one with the hishest number_of_reffers to come first, follow by the next and so on.

Is this possible and how can i do this in php.

Thanks for you help.

Answer

In the most simplest sense; you may just want to try this:

    <?php
        // SORTING ALGORITHM:
        // TO SORT IN THE OPPOSITE SENSE... 
        // (IE. ASCENDING [AS OPPOSED TO THE DEFAULT: DESCENDING]
        // CHANGE THE LESS THAN (<) BELOW TO GREATER THAN (>) 
        function orderByNumRef($arrPrev, $arrNext) {
            if ($arrPrev['number_of_reffers'] == $arrNext['number_of_reffers']) {
                return 0;
            }
            return ($arrPrev['number_of_reffers'] < $arrNext['number_of_reffers']) ? -1 : 1;
        }

        //GIVEN ARRAY - DYNAMIC OR HARD-CODED
        $arr = array(
            array(
                'refferrer'         => 'http://google.com/',
                'number_of_reffers' =>'15',
            ),
            array(
                'refferrer'         => 'https://facebook.com/',
                'number_of_reffers' =>'74',
            ),
            array(
                'refferrer'         => 'http://findy.com/',
                'number_of_reffers' =>'6',
            ),
        );


        //BEFORE SORTING:
        var_dump($arr);



        uasort($arr, 'orderByNumRef');

        //AFTER SORTING:
        var_dump($arr);

Hope it helps...

Comments