在抽獎、推薦、測試數據采樣等場景中,需要從數組中隨機抽取指定數量的元素。本文對比多種方法的性能、特性與適用場景。
| 方法 | 保留鍵名 | 性能 | 適用場景 | PHP 版本 |
|---|---|---|---|---|
| array_rand() + 重組 | 可選 | O(n) | 抽取鍵名、需保留關聯 | 所有 |
| shuffle() + array_slice() | 重置為 0 索引 | O(n) | 順序無關、數值索引數組 | 所有 |
| array_shuffle() (自定義) | 保留 | O(n) | 關聯數組亂序保留鍵 | 所有 |
| random_int() 循環 | 可控 | O(k) | 極大數組抽取極少元素 | 7.0+ |
<?php
$items = ['a' => '蘋果', 'b' => '香蕉', 'c' => '橙子', 'd' => '葡萄', 'e' => '西瓜'];
// 抽取 3 個鍵名
$randomKeys = array_rand($items, 3);
// 結果例:['b', 'd', 'a']
// 組合成新數組(保留鍵值對應)
$selected = [];
foreach ($randomKeys as $key) {
$selected[$key] = $items[$key];
}
// 結果:['b' => '香蕉', 'd' => '葡萄', 'a' => '蘋果']
// 簡寫(PHP 7.1+)
$selected = array_intersect_key($items, array_flip($randomKeys));
// 或
$selected = [];
foreach (array_rand($items, 3) as $key) {
$selected[$key] = $items[$key];
}
?>
array_rand() 返回單個鍵時為字符串,多個時為數組(PHP 7.1+ 修復)<?php
$items = ['蘋果', '香蕉', '橙子', '葡萄', '西瓜', '草莓', '芒果'];
// 原地打亂(修改原數組)
shuffle($items);
// 取前 3 個
$selected = array_slice($items, 0, 3);
// 結果:['葡萄', '蘋果', '芒果'](隨機順序,鍵名重置為 0,1,2)
// 不修改原數組
$copy = $items;
shuffle($copy);
$selected = array_slice($copy, 0, 3);
?>
缺點:關聯數組鍵名丟失、修改原數組(需複製)、大數組完整打亂浪費性能。
<?php
function arrayShuffleAssoc(array &$array): void {
$keys = array_keys($array);
shuffle($keys);
$shuffled = [];
foreach ($keys as $key) {
$shuffled[$key] = $array[$key];
}
$array = $shuffled;
}
$items = ['a' => '蘋果', 'b' => '香蕉', 'c' => '橙子', 'd' => '葡萄'];
arrayShuffleAssoc($items);
// $items 亂序但保留鍵名
// 取前 3 個
$selected = array_slice($items, 0, 3, true); // true 保留鍵名
?>
適用於:數組極大(百萬級)、只需抽取少量(如 100 個)、不可一次性載入內存。
<?php
function reservoirSample(iterable $source, int $k): array {
$reservoir = [];
$i = 0;
foreach ($source as $item) {
if ($i < $k) {
// 前 k 個直接放入
$reservoir[] = $item;
} else {
// 第 i+1 個元素,以 k/(i+1) 概率替換
$j = random_int(0, $i);
if ($j < $k) {
$reservoir[$j] = $item;
}
}
$i++;
}
return $reservoir;
}
// 使用:從生成器/迭代器抽取,無需載入全量數據
$largeData = function() {
for ($i = 0; $i < 1000000; $i++) {
yield "item_$i";
}
};
$sample = reservoirSample($largeData(), 100);
// 內存只佔用 100 個元素大小
?>
<?php
function weightedRandom(array $items, array $weights, int $count = 1): array {
// 構建累積權重
$cumWeights = [];
$sum = 0;
foreach ($weights as $w) {
$sum += $w;
$cumWeights[] = $sum;
}
$selected = [];
$keys = array_keys($items);
for ($i = 0; $i < $count; $i++) {
$rand = random_int(1, $sum);
// 二分查找
$index = 0;
while ($index < count($cumWeights) && $cumWeights[$index] < $rand) {
$index++;
}
$selected[] = $items[$keys[$index]];
}
return $selected;
}
// 使用
$prizes = ['一等獎', '二等獎', '三等獎', '參與獎'];
$weights = [1, 5, 20, 100]; // 權重比 1:5:20:100
$winners = weightedRandom($prizes, $weights, 10);
?>
<?php
$arr = range(1, 100000); // 10萬元素
$count = 100; // 抽取 100 個
// array_rand
$start = microtime(true);
for ($i = 0; $i < 100; $i++) {
$keys = array_rand($arr, $count);
$result = array_intersect_key($arr, array_flip($keys));
}
echo "array_rand: " . (microtime(true) - $start) . "s\n";
// shuffle + slice
$start = microtime(true);
for ($i = 0; $i < 100; $i++) {
$copy = $arr;
shuffle($copy);
$result = array_slice($copy, 0, $count);
}
echo "shuffle: " . (microtime(true) - $start) . "s\n";
// 典型輸出(僅供參考):
// array_rand: 0.045s
// shuffle: 0.180s
?>
結論:抽取少量元素用 array_rand();全量亂序用 shuffle();超大數據流用水塘抽樣。
<?php
class RecommendationEngine {
public function getRandomRecommendations(array $pool, int $count, array $exclude = []): array {
// 1. 過濾排除項
$candidates = array_diff_key($pool, array_flip($exclude));
// 2. 候選不足時補充策略
if (count($candidates) < $count) {
// 可選:從熱門池補充、降低推薦數量、返回所有
$count = min($count, count($candidates));
}
// 3. 隨機抽取
if ($count >= count($candidates)) {
return $candidates; // 全部返回
}
$keys = array_rand($candidates, $count);
return array_intersect_key($candidates, array_flip((array)$keys));
}
// 基於用戶行為的加權推薦
public function getWeightedRecommendations(array $pool, array $userInterests, int $count): array {
$weights = [];
foreach ($pool as $id => $item) {
$weight = 1; // 基礎權重
// 根據用戶興趣標籤加權
foreach ($userInterests as $interest => $interestWeight) {
if (isset($item['tags'][$interest])) {
$weight += $interestWeight;
}
}
$weights[$id] = $weight;
}
return $this->weightedRandomKeys($pool, $weights, $count);
}
private function weightedRandomKeys(array $pool, array $weights, int $count): array {
$cumWeights = [];
$sum = 0;
foreach ($weights as $w) {
$sum += $w;
$cumWeights[] = $sum;
}
$selected = [];
$keys = array_keys($pool);
for ($i = 0; $i < $count; $i++) {
$rand = random_int(1, $sum);
$index = 0;
while ($index < count($cumWeights) && $cumWeights[$index] < $rand) {
$index++;
}
$selected[$keys[$index]] = $pool[$keys[$index]];
}
return $selected;
}
}
?>