phparrayssortingassociative-array

Sort an associative array by values and preserve keys


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',
    etc...
);

Solution

  • 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
    )