-1

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.

Ukor
  • 324
  • 3
  • 15
  • I'm sure that in other examples you've seen, `usort` has been used. Can you explain why that did not solve your problem? – Don't Panic May 03 '16 at 23:00
  • @Don'tPanic I have no idea why they were not working, but using the answers below especially the one I accepted explained it better and has also helped me understand [PHP: usort Manuel](http://php.net/manual/en/function.usort.php) . Thank you. – Ukor May 03 '16 at 23:29

4 Answers4

3

You need usort

Given your array, you would then do this:

usort( $array, 'sort_by_referrer_count' );

var_dump($array);

// This will sort ascending
function sort_by_referrer_count( $a, $b ) {
    // Some defensive coding to ensure keys exist
    $a = ( isset( $a['number_of_referrers'] ) ) ? $a['number_of_referrers'] : 0;
    $b = ( isset( $b['number_of_referrers'] ) ) ? $b['number_of_referrers'] : 0;

    if ($a == $b) {
        return 0;
    }
    return ( $a < $b ) ? -1 : 1;
}

If you want descending, then you could do this (using the same function above):

usort( $array, 'sort_by_referrer_count' );
$array = array_reverse( $array );
random_user_name
  • 23,924
  • 7
  • 69
  • 103
1

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...

Poiz
  • 7,306
  • 2
  • 11
  • 17
-1

The easiest way I find to do it is by creating a new array with the number_of_reffers as the key. Then sort the new array with either ksort() or krsort(). This in the end leaves the original array intact. Otherwise creating the original array in the intended format would be better.

<?php
// original array
$array = array(
    array('refferrer' => 'http://google.com/', 'number_of_reffers' => '15'),
    array('refferrer' => 'https://facebook.com/', 'number_of_reffers' => '22'),
    array('refferrer' => 'none', 'number_of_reffers' => '74'),
    array('refferrer' => 'http://findy.com/', 'number_of_reffers' => '6')
);

$foo = array(); // new empty array

// loop through $array, assign the number_of_reffers as the key for the refferrer
foreach ($array as $key => $bar) {
    $foo[$bar['number_of_reffers']] = $bar['refferrer'];
}

/* 
    new array will be:
    array(
        '15' => 'http://google.com/',
        '22' => 'https://facebook.com/'
        etc .....
    )
*/


// use Ksort / Krsort to sort the key asc or desc
ksort($foo); // ascending order
#krsort($foo); // descending order

die('<pre>'.print_r($foo, true).'</pre>'); // pretty printing of sorted array
?>

As a function ....

<?php

Function Referrer_sort($array, $asc = true) {

    IF (!is_array($array)) { return 'not an array'; }

    $result = array();
    foreach ($array as $key => $value) {
        $result[$value['number_of_reffers']] = $value['refferrer'];
    }

    switch ($asc) {
        case false: krsort($result); return $result;
        default: ksort($result); return $result;
    }

}

$foo_asc = Referrer_sort($array);
$foo_desc = Referrer_sort($array, false);

die('<pre>Ascending:<br>'.print_r($foo_asc, true).'<br>Descending:<br>'.print_r($foo_desc, true).'</pre>');

?>

Changing the original array

Modifying the original array by changing the index key with the value of number_of_reffers.

<?php

Function Rebuild_Referrer_sort($array, $asc = true) {

    IF (!is_array($array)) { return 'not an array'; }

    $result = array();
    foreach ($array as $key => $value) {
        $result[$value['number_of_reffers']] = array('refferrer' => $value['refferrer'], 'number_of_reffers' => $value['number_of_reffers']);
    }

    switch ($asc) {
        case false: krsort($result); return $result;
        default: ksort($result); return $result;
    }

}


$foo_asc = Rebuild_Referrer_sort($array);
$foo_desc = Rebuild_Referrer_sort($array, false);

die('<pre>Ascending:<br>'.print_r($foo_asc, true).'<br>Descending:<br>'.print_r($foo_desc, true).'</pre>');

/**
  Returns:

Ascending:
Array
(
    [6] => Array
        (
            [refferrer] => http://findy.com/
            [number_of_reffers] => 6
        )

    [15] => Array
        (
            [refferrer] => http://google.com/
            [number_of_reffers] => 15
        )

    [22] => Array
        (
            [refferrer] => https://facebook.com/
            [number_of_reffers] => 22
        )

    [74] => Array
        (
            [refferrer] => none
            [number_of_reffers] => 74
        )

)

Descending:
Array
(
    [74] => Array
        (
            [refferrer] => none
            [number_of_reffers] => 74
        )

    [22] => Array
        (
            [refferrer] => https://facebook.com/
            [number_of_reffers] => 22
        )

    [15] => Array
        (
            [refferrer] => http://google.com/
            [number_of_reffers] => 15
        )

    [6] => Array
        (
            [refferrer] => http://findy.com/
            [number_of_reffers] => 6
        )

)
*/

?>
Brian
  • 1,025
  • 7
  • 13
  • Although this code may answer the question, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight May 04 '16 at 08:37
  • updated as requested. – Brian May 04 '16 at 18:31
-1

Try this:

<?php

$my_array;

//Sort Acceding 
usort($my_array, create_function('$a,$b', 'return (Int)$a["number_of_reffers"]-(Int)$b["number_of_reffers"];'));

//Or sort Descending
usort($my_array, create_function('$a,$b', 'return (Int)$b["number_of_reffers"]-(Int)$a["number_of_reffers"];'));
ChrisA
  • 197
  • 8