3 回答

TA貢獻(xiàn)1795條經(jīng)驗(yàn) 獲得超7個(gè)贊
有一個(gè)原生 PHP 函數(shù)可以實(shí)現(xiàn)此目的。
只需將一個(gè)值推入普通數(shù)組即可添加它:
$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);
結(jié)果$totals數(shù)組將是:
Array
(
? ? [hello] => 3
? ? [bye] => 2
? ? [John] => 1
)

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
將其構(gòu)建到一個(gè)類中將允許您根據(jù)需要?jiǎng)?chuàng)建計(jì)數(shù)器。它有一個(gè)私有變量,用于存儲(chǔ)每次調(diào)用的計(jì)數(shù)inc()(因?yàn)樗窃隽慷皇莂dd())。
該ordered()方法首先對計(jì)數(shù)器進(jìn)行排序(用于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
)

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以通過以下方式執(zhí)行此操作:
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);
你會(huì)得到類似的輸出
Array ( [hello] => 3 [bye] => 2 [John] => 1 )
- 3 回答
- 0 關(guān)注
- 179 瀏覽
添加回答
舉報(bào)