亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 161 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號