在laravel中计数组

时间:2015-07-31 23:57:21

标签: php mysql sql laravel

我当前的选择声明:

return User::select('id', 'created_at')
                    ->orderBy('created_at', 'desc')
                    ->get()
                    ->groupBy(function($date) {
                        return Carbon::parse($date->created_at)->format('Y m d');
                    });

目前返回

2015 07 28: [
{
id: 935,
created_at: "2015-07-28 23:00:20"
}
],

2015 07 27: [
{
id: 926,
created_at: "2015-07-27 17:13:58"
},
{
id: 925,
created_at: "2015-07-27 15:00:36"
},
{
id: 924,
created_at: "2015-07-27 13:37:00"
}
]

我只想要:

Date | Users
-----+------
7/28 | 1
7/27 | 3

1 个答案:

答案 0 :(得分:1)

您可以尝试按查询级别分组,如下所示,它会很快,试一试:)

return User::select(\DB::raw('id, count(id) numberOfUsers, DATE(created_at) dateOnly, DATE_FORMAT(created_at, "%m/%d" ) displayDate'))
                ->orderBy('created_at', 'desc')
                ->groupBy('dateOnly')
                ->get();

DATE(created_at) dateOnly会选择日期时间中的日期dateOnly

DATE_FORMAT(created_at, "%m/%d" ) displayDate这会将日期格式化为month/date => 04/07displayDate

count(id) numberOfUsersnumberOfUsers分组后选择每个组中dateOnly的用户数。

然后您可以根据需要使用这些日期,

EX:

$ users =>结果来自上述查询

    echo "<table border='1' style='border-collapse: collapse;'>";
    echo "<tr>";
    echo "<td>Date</td>";
    echo "<td>Users</td>";
    echo "</tr>";
    foreach($users as $user) {
        echo "<tr>";
        echo "<td>". $user->displayDate ."</td>"; // prints the formatted date.
        echo "<td>". $user->numberOfUsers ."</td>"; // prints the users count.
        echo "</tr>";
    }
    echo "</table>";

这是[{1}}

中提供的date formats