7

我想对以下名称进行排序

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

任何帮助将不胜感激,我在这方面花了很长时间,但无法直截了当地对数组进行正确排序。

4

1 回答 1

10

您想使用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
)
于 2012-09-22T21:17:52.417 回答