php - 从给定的出生日期计算年龄组
问题描述
在一个应用程序中,我有一个如下所示的选择框:
<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
吗?
另外,我想第一个开关盒应该有一个 or 因为你可能小于 18 岁。
像这样:case($age >= 18 && $age <= 24);
解决方案
您可以将不喜欢回答的null
值存储为他们的出生日期。然后,在检查用户的年龄组时,您可以检查一个null
值并在访问器中返回您不喜欢回答或未指定的选项:
public function getAgeGroupAttribute()
{
if ($this->birth_date === null) {
return 'Unspecified';
}
$age = $this->birth_date->diff(Carbon::now())->format('Y');
// ...
}
推荐阅读
- azure - 如何解决 azure iot readmessage 设备中的 Unhandle Exception:System.Net Socket.SocketException?
- python - 安装 pip 的问题(命令提示符)
- python-3.x - 在 **kwargs 中使用 f 字符串时出现语法错误
- php - 试图获取非对象 cms 传输的属性
- javascript - 如何修复“无法读取未定义的属性‘MakeCellsEditable’”错误
- android - 从 Okhttp3 响应中检索 JSON 对象
- r - ggplot中轴标签上括号内只有一个字符的上标
- python - 如何在 ctypes 中接收来自 .dll 的回调函数消息?
- xamarin - Xamarin listview 按钮单击获取命令参数值
- javascript - 来自平面 json 的分层 json 数据