我想对以下名称进行排序
Array ( [Jessie] => 2 [Sarah] => 3 [Simon] => 2 [John] => 2 [Kevin] => 1 [Canvasser] => 8 [canvasser] => 11 )
基于与其对应的值
我通过以下功能打印了名字
// 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);
其中$ canvassers只持有所有名称,例如。
$canvassers = array('Jessie', 'Simon', 'Jessie')
任何帮助都会非常感激,我已经花了这么长时间,但我无法直接对阵列进行正确排序。
答案 0 :(得分:6)
您希望使用asort()
- http://php.net/manual/en/function.asort.php - 按升序对值进行排序,或arsort()
- http://php.net/manual/en/function.arsort.php - 按降序排序。
鉴于此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
您将获得以下输出:
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
)