计算出生日期的年龄组

问题描述 投票:0回答:2

在一个应用程序中,我有一个看起来像这样的选择框:

<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之前,我会检查这实际上是一个约会吗?

另外,我想第一个开关盒应该有一个或因为你可能不到18岁。

像这样:case($age >= 18 && $age <= 24);

php laravel
2个回答
2
投票

您可以只是存储不想作为他们的出生日期的null值回答。然后,当检查用户的年龄组时,您可以检查null值并返回您不希望在您的访问者中回答或未指定的选项:

public function getAgeGroupAttribute()
{
    if ($this->birth_date === null) {
        return 'Unspecified';
    }

    $age = $this->birth_date->diff(Carbon::now())->format('Y');

    // ...
}

1
投票

您还可以将值0设置为PATNA

 <option value="0">Prefer not to answer</option>

并将你的开关盒与表壳一起使用

case($age >= 18 && $age <= 24);

我也会在这种情况下更改默认消息,只是出于一致性原因,但这样做可以解决问题。

当然,一种更健壮的方法是检查您接收的值是多少,如果它不是一个年龄,那么甚至不将它放在switch case中并将其重定向到else语句,但上述解决方案只是快速而简单。

© www.soinside.com 2019 - 2024. All rights reserved.