Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort PHP array by numerical values

I would like to sort the following names

Array ( [Jessie] => 2 [Sarah] => 3 [Simon] => 2 [John] => 2 [Kevin] => 1 [Canvasser] => 8 [canvasser] => 11 )

based on the values corresponding to them

I printed the names through the following function

// get canvasser individual names and count houses canvassed
    foreach ($canvassers as $key => $value) {
        // Add to the current group count if it exists
        if ( isset( $canvasser_counts[$value] ) ) {
            $canvasser_counts[$value]++;
        }
        // or initialize to 1 if it doesn't exist
        else {
            $canvasser_counts[$value] = 1;
        }
    }
    print_r($canvasser_counts);

where $canvassers simply held all the names eg.

$canvassers = array('Jessie', 'Simon', 'Jessie')

Any help would be really appreciated, I have spent so long on this but can't get my head straight to sort the array correctly.

like image 341
dev Avatar asked Sep 22 '12 21:09

dev


1 Answers

You want to use asort() - http://php.net/manual/en/function.asort.php - to sort the values in ascending order, or arsort() - http://php.net/manual/en/function.arsort.php - to sort in descending order.

Given this PHP:

$vals = array("Jessie" => 2, "Sara" => 3, "Simon" => 2, "John" => 2, "Kevin" => 1, "Canvasser" => 8, "canvasser" => 11 );
print_r($vals); // current order
asort($vals); // sort array
print_r($vals); // new order

You will get the following output:

Array
(
    [Jessie] => 2
    [Sara] => 3
    [Simon] => 2
    [John] => 2
    [Kevin] => 1
    [Canvasser] => 8
    [canvasser] => 11
)
Array
(
    [Kevin] => 1
    [Jessie] => 2
    [John] => 2
    [Simon] => 2
    [Sara] => 3
    [Canvasser] => 8
    [canvasser] => 11
)
like image 81
doublesharp Avatar answered Sep 24 '22 10:09

doublesharp