【发布时间】:2018-08-30 17:24:22
【问题描述】:
在一个应用程序中,我有一个如下所示的选择框:
<select name="AgeGroup" class="form-control" id="AgeGroup">
<option value="18-24" selected=""18-24</option>
<option value="18-24">18-24 years</option>
<option value="25-34">25-34 years</option>
<option value="35-44">35-44 years</option>
<option value="45-54">45-54 years</option>
<option value="55-64">55-64 years</option>
<option value="65 Plus">65 years or over</option>
<option value="PTNA">Prefer not to answer</option>
</select>
除此之外,我还询问了用户的出生日期,但同时询问用户似乎很愚蠢,因为您肯定可以从提供的出生日期算出给定的年龄组吗?
当我收集出生日期时,我有一个简单的变异器来获取用户的年龄,如下所示:
/**
* Calculate the user's age in years given their date of birth
*
* @return void
*/
public function getAgeAttribute()
{
$this->birth_date->diff(Carbon::now())->format('Y');
}
然后我意识到我什至不需要年龄属性来计算年龄组,所以我制作了另一个这样的访问器:
/**
* Infer the users age group given their date of birth
*
* @return void
*/
public function getAgeGroupAttribute()
{
$age = $this->birth_date->diff(Carbon::now())->format('Y');
switch($age){
case($age <= 24);
return "18 - 24";
break;
case ($age <= 34);
return "25 - 34";
break;
case ($age <= 44);
return "35 - 44";
break;
case ($age <= 54);
return "45 - 54";
break;
case ($age <= 64);
return "55 - 64";
break;
case ($age > 64);
return "Over 65";
break;
default:
return "Unspecified age group";
}
}
但我担心的是,如果他们实际上没有选择提供年龄怎么办?由于此表单带有“不想说”的选项。
我是不是要检查一下这实际上是在我做$user->age_group 之前的日期?
另外,我想第一个 switch 案例应该有一个 or 因为你可能小于 18 岁。
像这样:case($age >= 18 && $age <= 24);
【问题讨论】: