【问题标题】:Calculating age group from a given date of birth从给定的出生日期计算年龄组
【发布时间】: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-&gt;age_group 之前的日期?

另外,我想第一个 switch 案例应该有一个 or 因为你可能小于 18 岁。

像这样:case($age &gt;= 18 &amp;&amp; $age &lt;= 24);

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以将不想回答存储为null 值作为他们的出生日期。然后,在检查用户的年龄组时,您可以检查 null 值并在访问器中返回您的 prefer not to answerunspecified 选项:

    public function getAgeGroupAttribute()
    {
        if ($this->birth_date === null) {
            return 'Unspecified';
        }
    
        $age = $this->birth_date->diff(Carbon::now())->format('Y');
    
        // ...
    }
    

    【讨论】:

      【解决方案2】:

      你也可以把值 0 代替 PTNA

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

      并将您的开关盒与外壳一起使用

      case($age &gt;= 18 &amp;&amp; $age &lt;= 24);

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

      当然,更可靠的方法是检查您收到的值是什么,如果不是年龄,则甚至不要将其放入 switch case 并将其重定向到 else 语句,但上述解决方案很快并且简单的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-02
        • 2019-01-29
        相关资源
        最近更新 更多