星座劃分以「太陽穿越黃道十二宮」為依據,每年日期固定(閏年僅影響 2 月天數,不改變星座分界點)。本文提供一個健壯、可擴展的 get_constellation() 函數,包含參數驗證、邊界精準判定、單元測試用例。
<?php
/**
* 根據月份、日期返回中文星座名稱
*
* @param int $month 1-12
* @param int $day 1-31
* @return string|false 星座名稱或 false (參數非法)
*/
function get_constellation(int $month, int $day) {
// 1. 參數合法性檢查
if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
return false;
}
// 進一步校驗日期合法性 (如 2 月 30 日)
if (!checkdate($month, $day, 2000)) { // 任意閏年
return false;
}
// 2. 星座分界點:「該星座開始日期」=> 星座名
// 索引 0 代表 1 月,以此類推
$boundaries = [
1 => ['date' => 20, 'name' => '寶瓶座'], // 1/20 ~ 2/18
2 => ['date' => 19, 'name' => '雙魚座'], // 2/19 ~ 3/20
3 => ['date' => 21, 'name' => '白羊座'], // 3/21 ~ 4/19
4 => ['date' => 20, 'name' => '金牛座'], // 4/20 ~ 5/20
5 => ['date' => 21, 'name' => '雙子座'], // 5/21 ~ 6/21
6 => ['date' => 22, 'name' => '巨蟹座'], // 6/22 ~ 7/22
7 => ['date' => 23, 'name' => '獅子座'], // 7/23 ~ 8/22
8 => ['date' => 23, 'name' => '處女座'], // 8/23 ~ 9/22
9 => ['date' => 23, 'name' => '天秤座'], // 9/23 ~ 10/23
10 => ['date' => 24, 'name' => '天蠍座'], // 10/24 ~ 11/22
11 => ['date' => 22, 'name' => '射手座'], // 11/23 ~ 12/21
12 => ['date' => 22, 'name' => '摩羯座'], // 12/22 ~ 1/19
];
// 3. 邏輯:若日期 >= 當月分界點 => 當月星座,否則 => 上月星座
$current = $boundaries[$month];
if ($day >= $current['date']) {
return $current['name'];
}
// 回退到上個月 (1 月回退到 12 月)
$prevMonth = $month === 1 ? 12 : $month - 1;
return $boundaries[$prevMonth]['name'];
}
// 別名兼容
function yige_constellation($month, $day) {
return get_constellation((int)$month, (int)$day);
}
?>
<?php
$tests = [
// [month, day, expected]
[1, 19, '摩羯座'], // 邊界前一天
[1, 20, '寶瓶座'], // 邊界當天
[2, 18, '寶瓶座'],
[2, 19, '雙魚座'],
[3, 20, '雙魚座'],
[3, 21, '白羊座'],
[4, 19, '白羊座'],
[4, 20, '金牛座'],
[5, 20, '金牛座'],
[5, 21, '雙子座'],
[6, 21, '雙子座'],
[6, 22, '巨蟹座'],
[7, 22, '巨蟹座'],
[7, 23, '獅子座'],
[8, 22, '獅子座'],
[8, 23, '處女座'],
[9, 22, '處女座'],
[9, 23, '天秤座'],
[10, 23, '天秤座'],
[10, 24, '天蠍座'],
[11, 22, '天蠍座'],
[11, 23, '射手座'],
[12, 21, '射手座'],
[12, 22, '摩羯座'],
[12, 31, '摩羯座'],
[2, 29, '雙魚座'], // 閏年日期
[13, 1, false], // 非法月份
[1, 32, false], // 非法日期
[2, 30, false], // 非法日期 (2月30日)
];
echo "測試開始...\n";
foreach ($tests as [$m, $d, $exp]) {
$res = get_constellation($m, $d);
$status = $res === $exp ? '✅ PASS' : '❌ FAIL';
echo "$status get_constellation($m, $d) => '$res' (期望: '$exp')\n";
}
echo "測試結束。\n";
<?php
function fetch_horoscope(string $constellation, string $period = 'today') {
// 對接第三方 API (如 juhe.cn, tianapi.com)
// 返回 ['love' => 4, 'work' => 3, 'money' => 5, 'summary' => '...']
// 建議快取 6-12 小時,避免頻繁請求
}
$constellation = get_constellation(4, 20); // 金牛座
$horoscope = fetch_horoscope($constellation);
echo "今日$constellation運勢:{$horoscope['summary']}";
checkdate() 僅用於驗證輸入合法性。ChineseCalendar 庫)。