按年龄类别对用户进行分组和计数

时间:2019-01-02 21:39:18

标签: php laravel

我试图通过循环遍历用户以将其分为20岁以下的两个类别,以便使用Carbon来计算年龄值。

Array.Copy(x, 0, x, 0, x.Length);

}

    public function groupAndCountBasedOnAge($users) {
 // i'm giving the array keys & values
    $ageGroups = array('younger than 20' => 0,
                       'older than 20' => 0); 


foreach($users as $u) {

    $now = Carbon::now();
    $u->age = Carbon::createFromFormat('Y-m-d', $u->birth_date);
    $u->age = $now->diffInYears($u->age);  // getting actual age value for each user

    if($u->age < 20 ) {
        $ageGroups[younger than 20'] += 1;
    }
    elseif($u->age > 20 ) {
        $ageGroups['older than 20'] += 1;
    }

return $ageGroups;

}

}     但是dd($ users)总是返回相同的数组,无论我如何更改:

public function index() {

$users = DB::table('users')->get();

$users = $this->groupAndCountBasedOnAge($users);

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

2 个答案:

答案 0 :(得分:0)

尝试:

    $age = Carbon::now()->diffInYears(Carbon::parse($u->birth_date));

然后:

    if ($age>20) 
    {
        $sol['greater']++
    }
    else
    {
        $sol['lesser']++
    }

    return $sol;

答案 1 :(得分:0)

您可以使用partition()Count()Laravel Collections方法。

use Illuminate\Support\Carbon;

//

public function index() {

    $users = DB::table('users')->get();
    $users = $this->groupAndCountBasedOnAge($users);

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

public function groupAndCountBasedOnAge($users)
{
    list($under, $equalOrAbove) = collect($users)->partition(function ($user) {
        return Carbon::now()
            ->diffInYears(Carbon::createFromFormat('Y-m-d', $user->birth_date)) < 20;
    });

    return [
        'underTwenty'  => [
            'users' => $under->all(),
            'count' => $under->count()
        ],
        'equalOrAboveTwenty' => [
            'users' => $equalOrAbove->all(),
            'count' => $equalOrAbove->count()
        ]
    ];
}

注意

我也对用户进行了分组,因为我猜想您想要这样做(根据您的方法名称)。