php - PHP 中的什么集合可以对出现次数进行计数和排序

标签 php arrays collections

使用 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/

相关文章:

php - 防止php中的sql注入(inject)

php - 在包含中传递 smarty 变量(使用 Codeigniter )

java - 登录网站到外部门户

python - 以 Python 方式使用列表对 numpy 数组进行索引

PHP/MySQL - 如果变量不存在则更新数组

Java 8 : getting default values for a collection with nested Optionals

php - 从 YouTube API v3 中的播放列表获取所有视频信息

javascript - 解析之前更改 Meteor.Collection

c# - 为什么 C# 集合初始化器以这种方式工作?

C# DLL 的包装器