需求:預先定義問候語陣列,依「天、週、月」等時間間隔自動輪換,無需人工維護,且對 SEO 友好(伺服端渲染)。
<?php
function randomQuoteByInterval($timeBase, array $quotes) {
$timeBase = intval($timeBase); // 確保整數
$count = count($quotes); // 陣列長度
$index = $timeBase % $count; // 取模得到索引
return $quotes[$index];
}
<?php
$quotes = [
'沒有動物在製作這段程式碼時受到傷害。',
'不錯的代碼片段',
'取模運算符真強大!',
'PHP 真酷。',
];
// 每日換一句(z = 0~365)
$dayOfYear = (int)date('z');
echo randomQuoteByInterval($dayOfYear, $quotes);
// 其他間隔選項
// date('W') 每週(ISO 週數 1~53)
// date('m') 每月(1~12)
// date('Y') 每年
// date('h') 每小時
// date('i') 每分鐘
<?php
function weightedRandomQuote($timeBase, array $quotes, array $weights = null) {
$weights = $weights ?? array_fill(0, count($quotes), 1);
$total = array_sum($weights);
$index = ($timeBase % $total);
$accum = 0;
foreach ($weights as $i => $w) {
$accum += $w;
if ($index < $accum) return $quotes[$i];
}
return $quotes[0];
}
// 多語系
$quotes = [
'zh-TW' => ['早安!', '哈囉!', '你好呀!'],
'en' => ['Good morning!', 'Hello!', 'Hi there!'],
];
$lang = $_GET['lang'] ?? 'zh-TW';
echo randomQuoteByInterval((int)date('z'), $quotes[$lang]);
<?php
// quotes 表:id, content, lang, weight, enabled
$day = (int)date('z');
$stmt = $pdo->prepare("SELECT content FROM quotes WHERE enabled=1 AND lang=? ORDER BY id LIMIT 1 OFFSET ?");
$stmt->execute(['zh-TW', $day % $totalCount]);
echo $stmt->fetchColumn();
以「時間基準取模陣列長度」為核心,輕鬆實現日/週/月/時自動輪換,零維護、高效能、SEO 友好。