按年龄数组分组返回空

时间:2019-01-02 10:33:12

标签: php laravel

我正在尝试计算用户年龄,然后将这些结果分组如下:

public function setAge($users)
{
    if($users)
        foreach($users as $user)
        {
            $now    = Carbon::now();
            $u->age = Carbon::createFromFormat('Y-m-d', $u->birth_date);
            $u->age = $now->diffInYears($u->age)
        }

    return $users;
}

public function groupByAge($users)
{
    $ageGroups = ['less than 20', 'more than 20'];
    foreach ($users as $u) 
       switch($u->age) {
           case ($u->age < 20)
               $ageGroups['less than 20'] += 1;
               break;
           case($u->age > 20)
               $ageGroups['more than 20'] += 1;
               break;
       }

    return $age;
}           

public function index()
{
    $users = DB::table('users')->get;
    $users = $this->setAge($users);
    $users = $this->groupByAge($users);

    dd($groupByAge);

    return view('/users/',['users'=> $users]);
}

但是当我dd($groupByAge)总是收到时

  

空数组,例如('key'=> 0)

我不确定是否正确传递了$users或发出了什么。

3 个答案:

答案 0 :(得分:1)

/**
 * @return array()
 */
public function setAge($users) {
  if($users) {
    foreach($users as &$user) {
      $now = Carbon::now();
      $user->age = Carbon::createFromFormat('Y-m-d', $user->birth_date);
      $user->age = $now->diffInYears($user->age);
    }
  }
 return $users;
}

/**
 * @return array()
 */
public function groupByAge($users) {
   $ageGroups = ['less than 20', 'more than 20'];
   $ageGroup = [];
    foreach ($users as $u) { 
        switch($u->age) {
          case ($u->age < 20) :
             $ageGroup['less_then_20'] = 1;
          break;
         case($u->age >= 20) :
             $ageGroup['more_than_20'] = 1;
         break;
         default:
             $ageGroup['error'] = 'error';
         break;
     }
   }
   return $ageGroup;
 }           

  public function index() {
    $users = DB::table('users')->get;
    $users = $this->setAge($users);
    $users = $this->groupByAge($users);

    print_r("<pre>");
    print_r($users);
    print_r("</pre>");die();

    return view('/users/',['users'=> $users]);
 }

答案 1 :(得分:1)

碳提供了一种直接计算年龄的方法。因此,假设$birth_date已经强制转换为Carbon实例,则可以在其上调用age

我不确定您是否只想统计特定年龄段的用户,或者是否要将其分组。如标题所示,将用户分为年龄组,您可以执行以下操作:

public function index() {
    $groupedUsers = User::all()->mapToGroups(function($user, $key) {
        if ($user->birth_date->age < 20) {
            $ageGroups['less than 20'][] = $user
        } else {
            $ageGroups['more than 20'][] = $user
        }

        return $ageGroups;
    });


    return view('/users/',[
    'users'=> $groupedUsers
    ]);
 }

答案 2 :(得分:0)

您应该尝试以下操作:

public function index() {
    $users = DB::table('users')->get;
    $users = $this->setAge($users);
    $users = $this->groupByAge($users);
    dd($users); exit();
    return view('/users/',[
      'users'=> $users]);

}