萬盛學電腦網

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

PHP 從陣列隨機取值:rand() 與 array_rand() 實作比較

需求:在文章側邊欄隨機顯示公司 12 個業務廣告語。本文比較兩種隨機取值方法,並說明擴充性考量。

方法一:rand() 產生索引

<?php
$ads = [
    '廣告語 1: 專業服務,值得信賴',
    '廣告語 2: 品質保證,售後無憂',
    '廣告語 3: 十年經驗,技術領先',
    '廣告語 4: 客製化方案,滿足需求',
    '廣告語 5: 24小時客服,隨時響應',
    // ... 共 12 筆
];

$index = rand(0, count($ads) - 1);
echo $ads[$index];
?>

方法二:array_rand() 內建函式

<?php
$ads = [
    'a' => '廣告語 1',
    'b' => '廣告語 2',
    'c' => '廣告語 3',
    // ...
];

// 取 1 個隨機鍵名
$random_key = array_rand($ads, 1);
echo "鍵名: $random_key, 值: {$ads[$random_key]}";

// 取 3 個不重複隨機鍵名
$random_keys = array_rand($ads, 3);
foreach ($random_keys as $key) {
    echo "{$key} => {$ads[$key]}<br>";
}
?>

兩者比較

特性rand() + 索引array_rand()
適用陣列類型索引陣列 (0,1,2...)索引/關聯陣列皆可
回傳值索引數字鍵名 (字串或整數)
多值不重複需自行實作 (shuffle/array_unique)原生支援 array_rand($arr, 3)
效能極快極快 (內建 C 實作)
隨機品質PHP 7.1+ 使用 Mersenne Twister同 rand()

進階:加權隨機 (廣告曝光權重)

<?php
$ads = [
    ['text' => '頂級廣告位', 'weight' => 50],   // 50% 機率
    ['text' => '優質廣告位', 'weight' => 30],   // 30%
    ['text' => '一般廣告位', 'weight' => 20],   // 20%
];

function weighted_rand(array $items) {
    $total = array_sum(array_column($items, 'weight'));
    $rand = mt_rand(1, $total);
    
    foreach ($items as $item) {
        $rand -= $item['weight'];
        if ($rand <= 0) return $item['text'];
    }
    return $items[0]['text'];  // fallback
}

echo weighted_rand($ads);
?>

擴充性建議:資料庫驅動

硬編碼陣列難以維護,建議改為資料表:

CREATE TABLE ads (
    id INT PRIMARY KEY AUTO_INCREMENT,
    content VARCHAR(255) NOT NULL,
    weight INT DEFAULT 1,
    status TINYINT DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- PHP 查詢 (PDO)
$stmt = $pdo->query("SELECT content, weight FROM ads WHERE status=1");
$ads = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo weighted_rand($ads);

安全性補充

  • 輸出廣告內容時記得 htmlspecialchars() 防 XSS
  • 若廣告含連結,驗證 URL 合法性
  • 考慮 CSP (Content Security Policy) 限制內聯腳本
copyright © 萬盛學電腦網 all rights reserved