为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
拉丁的传说 2023-11-03 16:02:28
使用 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]这已经存在了吗?
查看完整描述

3 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

有一个原生 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 them

asort($totals);


// If you want to sort them reversed

arsort($totals);

结果$totals数组将是:


Array

(

    [hello] => 3

    [bye] => 2

    [John] => 1

)


查看完整回答
反对 回复 2023-11-03
?
Qyouu

TA贡献1786条经验 获得超11个赞

将其构建到一个类中将允许您根据需要创建计数器。它有一个私有变量,用于存储每次调用的计数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

)


查看完整回答
反对 回复 2023-11-03
?
皈依舞

TA贡献1851条经验 获得超3个赞

您可以通过以下方式执行此操作:


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 )


查看完整回答
反对 回复 2023-11-03
  • 3 回答
  • 0 关注
  • 79 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信