php 根据出生日月判断星座

前言

注意:由于此函数使用了 each() 函数,故不支持 PHP7+ 环境下运行。

该函数用于判断星座,通过传入日月参数来完成判断,语法如下。

getConstellation($month, $day)
  1. $month:月(number)
  2. $day:日(number)

code

函数只完成了运算,并没有做太多参数判断及约束。

function getConstellation($month, $day){//参数为 number 类型

# 1.检查参数有效性(月日必须大于1且小于31)
if(($month < 1 || $month > 12) || ($day < 1 || $day > 31)) return false;//如不符合直接返回false退函数

# 2.星座名称及开始日期映射集合
$constellations = [
    ['20' => '水瓶座'], ['19' => '双鱼座'], ['21' => '白羊座'], ['20' => '金牛座'],
    ['21' => '双子座'], ['22' => '巨蟹座'], ['23' => '狮子座'], ['23' => '处女座'],
    ['23' => '天秤座'], ['24' => '天蝎座'], ['22' => '射手座'], ['22' => '魔羯座']
];

# 3.通过list()接收星座映射集合的键与值,然后进行判断(它的值由每个each()取出)
/*
* @ list() - $constellation_key: 接收键(key)
* @ list() - $constellation_value: 接收值(value)
* @ echo(): 提供键与值(抽取星座映射集合的键与值)
*/
list($constellation_key, $constellation_value) = each($constellations[(int)$month - 1]);
    if($day < $constellation_key){//[日]小于当前键(key)则进行深度判断
    	//再次判断,并接收最后的键与值(即对应星座键与值)
        list($constellation_key, $constellation_value) = 
        each($constellations[($month - 2 < 0) ? $month = 11 : $month -= 2]);
    }
    # 4.返回值(value)即可
    return $constellation_value;
}
// ! 注意: 在 PHP7+ 版本中 "each()" API 已被废弃,所以该函数只能在 PHP5+ 中使用。 
echo getConstellation(3,9);//双鱼座

可根据需求进行删改。

发布了269 篇原创文章 · 获赞 426 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/weixin_44198965/article/details/104505051