PHP 中的哪些集合可以对发生次数进行计数和排序

使用 PHP 7.3/7.4 我想使用/创建一个键值集合。我想多次按同一个键。每次该值都应该递增(第一次该值为 1)。最后,我需要获取按值排序的键值对。


例如


$somecollection = ???

$somecollection->add('hello')

$somecollection->add('bye')

$somecollection->add('hello')

$somecollection->add('John')

$somecollection->add('bye')

$somecollection->add('hello')

应该返回


$ordered = $somecollection->ordered()

dump($ordered) --> ['hello' -> 3, 'bye' -> 2, 'john' ->1]

这已经存在了吗?


拉丁的传说
浏览 83回答 3
3回答

一只萌萌小番薯

有一个原生 PHP 函数可以实现此目的。只需将一个值推入普通数组即可添加它:$values = [];$values[] = 'hello';$values[] = 'bye';$values[] = 'hello';$values[] = 'John';$values[] = 'hello';$values[] = 'bye';// Count the unique instances in the array$totals = array_count_values($values);// If you want to sort themasort($totals);// If you want to sort them reversedarsort($totals);结果$totals数组将是:Array(    [hello] => 3    [bye] => 2    [John] => 1)

Qyouu

将其构建到一个类中将允许您根据需要创建计数器。它有一个私有变量,用于存储每次调用的计数inc()(因为它是增量而不是add())。该ordered()方法首先对计数器进行排序(用于arsort保持键对齐)...class Counter {    private $counters = [];        public function inc ( string $name ) : void {        $this->counters[$name] = ($this->counters[$name] ?? 0) + 1;    }        public function ordered() : array {        arsort($this->counters);        return $this->counters;    }}所以$counter = new Counter();$counter->inc("first");$counter->inc("a");$counter->inc("2");$counter->inc("a");print_r($counter->ordered());给...Array(    [a] => 2    [first] => 1    [2] => 1)

皈依舞

您可以通过以下方式执行此操作:function count_array_values($my_array, $match) {    $count = 0;     foreach ($my_array as $key => $value)     {         if ($value == $match)         {             $count++;         }     }        return $count; } $array = ["hello","bye","hello","John","bye","hello"];$output =[];foreach($array as $a){    $output[$a] = count_array_values($array, $a); }arsort($output);print_r($output);你会得到类似的输出Array ( [hello] => 3 [bye] => 2 [John] => 1 )
打开App,查看更多内容
随时随地看视频慕课网APP