Current Location: Home> Latest Articles> How to Categorize and Analyze Data Weekly in ThinkPHP

How to Categorize and Analyze Data Weekly in ThinkPHP

gitbox 2025-08-04

How to Categorize Data in ThinkPHP

In the ThinkPHP (TP) framework, data categorization is typically achieved using Models. A model corresponds to a database table and supports both ORM operations and native SQL-style DB operations. ORM offers a clean and maintainable structure, while DB operations provide more flexibility and control.

For example, for a User model, you can retrieve user data using User::find(). Through model query methods, it's easy to filter, sort, and paginate data.

How to Group Data by Week

Fetch Data Within a Specific Time Range

To group data by week, the first step is to fetch data within a specific time range. Here's how to retrieve records from the past month:

// Fetch data from the past month
$data = User::where('created_at', '>=', date('Y-m-d', strtotime('-1 month')))
            ->get();

Once retrieved, the data can be sorted by date and prepared for weekly grouping.

Group Data by Week Number

Using PHP’s date('W') function, you can group the data by week numbers as shown below:

// Group data by week number
$dataByWeek = [];
foreach ($data as $item) {
    $weekNum = date('W', strtotime($item->created_at));
    if (!isset($dataByWeek[$weekNum])) {
        $dataByWeek[$weekNum] = [];
    }
    $dataByWeek[$weekNum][] = $item;
}

Each key represents a week number, and the corresponding value contains the data for that week.

Count Data for Each Week

To analyze user registrations, for instance, you can count the number of users registered per week like this:

// Count user registrations per week
$regCountByWeek = [];
foreach ($dataByWeek as $weekNum => $weekData) {
    $regCount = count($weekData);
    $regCountByWeek[$weekNum] = $regCount;
}

You can apply the same logic to count logins, orders, or other metrics.

Conclusion

Grouping and analyzing data by week is a common requirement in ThinkPHP development. By using model queries to fetch data and leveraging date functions to organize it weekly, you can efficiently perform insightful data analysis and support better business decisions.