統計陣列中出現頻率最高的前 N 個元素,是報表、日誌分析、推薦系統的高頻需求。PHP 內建函數組合可在幾行程式碼內優雅解決。
array_count_values(array $array):統計每個值出現次數,回傳 [值 => 次數] 關聯陣列arsort(array &$array):依值由大到小排序,保持鍵值關聯array_slice(array $array, int $offset, int $length):取前 N 筆<?php
/**
* 取得陣列中出現頻率最高的前 $topN 個值
* @param array $data 數值陣列
* @param int $topN 取前幾名,預設 10
* @return array [值 => 次數] 依頻率降序
*/
function topFrequentValues(array $data, int $topN = 10): array
{
if (empty($data)) return [];
// 1. 統計頻率
$freq = array_count_values($data);
// 2. 依頻率降序排序(保持鍵值關聯)
arsort($freq);
// 3. 取前 N
return array_slice($freq, 0, $topN, true);
}
// === 示範 ===
// 產生 1000 個 1~1000 隨機數
$data = [];
for ($i = 0; $i < 1000; $i++) {
$data[] = random_int(1, 1000);
}
$top10 = topFrequentValues($data, 10);
echo "出現頻率最高的前 10 個數值:\n";
foreach ($top10 as $value => $count) {
printf("數字:%d 出現 %d 次\n", $value, $count);
}
?>
出現頻率最高的前 10 個數值: 數字:255 出現 6 次 數字:443 出現 5 次 數字:906 出現 5 次 數字:623 出現 5 次 數字:586 出現 4 次 數字:660 出現 4 次 數字:873 出現 4 次 數字:208 出現 4 次 數字:247 出現 4 次 數字:240 出現 4 次
<?php
function bottomFrequentValues(array $data, int $topN = 10): array
{
$freq = array_count_values($data);
asort($freq); // 升序
return array_slice($freq, 0, $topN, true);
}
?>
<?php
$text = "PHP 是最好的語言 PHP 很強 PHP 很快";
$words = preg_split('/\s+/', $text);
$topWords = topFrequentValues($words, 5);
// ['PHP' => 3, '是' => 1, '最好的' => 1, '語言' => 1, '很強' => 1]
?>
<?php
$orders = [
['user_id' => 1, 'amount' => 100],
['user_id' => 2, 'amount' => 200],
['user_id' => 1, 'amount' => 50],
];
// 統計下單次數最多的用戶
$userIds = array_column($orders, 'user_id');
$topUsers = topFrequentValues($userIds, 5);
?>
<?php
function topFrequentLarge(iterable $data, int $topN = 10): array
{
$freq = [];
foreach ($data as $value) {
$freq[$value] = ($freq[$value] ?? 0) + 1;
// 可選:定期清理低頻項目以控制記憶體
if (count($freq) > 100000) {
arsort($freq);
$freq = array_slice($freq, 0, $topN * 10, true);
}
}
arsort($freq);
return array_slice($freq, 0, $topN, true);
}
// 使用 Generator 逐行讀取大檔案
function readNumbers(string $file): Generator
{
$fh = fopen($file, 'r');
while (($line = fgets($fh)) !== false) {
yield (int)trim($line);
}
fclose($fh);
}
$top = topFrequentLarge(readNumbers('huge_numbers.txt'), 10);
?>
| 資料量 | array_count_values 耗時 | 記憶體峰值 | 備註 |
|---|---|---|---|
| 1 萬 | ~1 ms | ~2 MB | 極快 |
| 100 萬 | ~80 ms | ~50 MB | 可接受 |
| 1 千萬 | ~1.2 s | ~500 MB | 建議分批/資料庫聚合 |
array_count_values 只接受 int 或 string,物件/資源會報警告並跳過'php' !== 'PHP',統計前建議 array_map('strtolower', $data)arsort(保持鍵值),不可用 rsort(會重置鍵為 0,1,2...)三行核心程式碼解決 Top-K 頻率統計,是 PHP 內建函數威力的經典展現。下次做報表、分析日誌、產生標籤雲時,直接套用這個模式即可。