使用 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]
这已经存在了吗?
最佳答案
将其构建到一个类中将允许您根据需要创建计数器。它有一个私有(private)变量,用于存储每次调用 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
)
关于php - PHP 中的什么集合可以对出现次数进行计数和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63603776/