萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 統計陣列出現頻率最高的 Top 10 數值:array_count_values + arsort 實戰

經典 Top-K 問題

統計陣列中出現頻率最高的前 N 個元素,是報表、日誌分析、推薦系統的高頻需求。PHP 內建函數組合可在幾行程式碼內優雅解決。

核心函數組合

  1. array_count_values(array $array):統計每個值出現次數,回傳 [值 => 次數] 關聯陣列
  2. arsort(array &$array):依值由大到小排序,保持鍵值關聯
  3. 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 次

進階變體

1. 取頻率最低的 Top N(長尾分析)

<?php
function bottomFrequentValues(array $data, int $topN = 10): array
{
    $freq = array_count_values($data);
    asort($freq); // 升序
    return array_slice($freq, 0, $topN, true);
}
?>

2. 字串陣列(單詞統計、標籤雲)

<?php
$text = "PHP 是最好的語言 PHP 很強 PHP 很快";
$words = preg_split('/\s+/', $text);
$topWords = topFrequentValues($words, 5);
// ['PHP' => 3, '是' => 1, '最好的' => 1, '語言' => 1, '很強' => 1]
?>

3. 多維陣列特定欄位統計

<?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);
?>

4. 記憶體優化:超大陣列分批處理

<?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 內建函數威力的經典展現。下次做報表、分析日誌、產生標籤雲時,直接套用這個模式即可。

copyright © 萬盛學電腦網 all rights reserved