Sort PHP array by numeric 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 their respective values

I printed the names using 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 just contained all the names, for example.

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

Any help would really be appreciated, I spent so long on it, but can't figure out how to sort the array correctly.

+4
source share
1 answer

Do you want to use asort() - http://php.net/manual/en/function.asort.php - sort the values ​​in ascending order or arsort() - http://php.net/manual/en/function.arsort .php - 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 result:

 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 ) 
+6
source

Source: https://habr.com/ru/post/1435695/


All Articles