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
)

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
)

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 )
- 3 回答
- 0 關注
- 161 瀏覽
添加回答
舉報