Current Location: Home> Latest Articles> How to aggregate data using array_reduce in array_chunk

How to aggregate data using array_reduce in array_chunk

M66 2025-04-26

How to combine array_reduce in array_chunk to group and aggregate data in array?

In PHP, array_chunk and array_reduce are two very powerful array operation functions. array_chunk can divide a large array into multiple small arrays, while array_reduce can recursively process elements in the array and then aggregate them. In some cases, we want to group the arrays and do some sort of aggregation operation after grouping. This article will explain how to combine these two functions to achieve this goal.

1. Basic usage of array_chunk function

array_chunk is a function in PHP that divides an array into multiple small arrays. It divides the original array into several subarrays according to the specified size, returning a two-dimensional array. For example:

 $array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunks = array_chunk($array, 3);
print_r($chunks);

The output result is:

 Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )
    [2] => Array
        (
            [0] => 7
            [1] => 8
            [2] => 9
        )
)

In this example, array_chunk divides the original array into three subarrays of size 3.

2. Basic usage of array_reduce function

The array_reduce function accepts an array and a callback function as parameters and performs a "reduce" operation on elements in the array. It starts with the first element of the array and passes the current element together with the result of the previous element to the callback function, eventually returning a single value. For example:

 $array = [1, 2, 3, 4, 5];
$sum = array_reduce($array, function($carry, $item) {
    return $carry + $item;
});
echo $sum;  // Output 15

In this example, array_reduce accumulates elements in the array and finally returns the sum of the array.

3. Combine array_chunk and array_reduce to group and aggregate data

Now that we know the basic usage of array_chunk and array_reduce , we can try to combine them to implement grouping and aggregation of arrays.

Suppose we have an array containing user order data, we want to group orders by user ID and calculate the total order amount for each user. We can first use array_chunk to group by user ID, and then use array_reduce to aggregate and calculate each set of data.

 // Assume that the following order data is available,Each order contains one user_id and amount amount
$orders = [
    ['user_id' => 1, 'amount' => 100],
    ['user_id' => 2, 'amount' => 200],
    ['user_id' => 1, 'amount' => 150],
    ['user_id' => 3, 'amount' => 300],
    ['user_id' => 2, 'amount' => 50],
    ['user_id' => 1, 'amount' => 200],
];

// use array_chunk according to user_id Group orders
$chunks = array_chunk($orders, 2);  // Assume that there are at most two orders per group

// use array_reduce Aggregate order amounts per group
$result = array_map(function($chunk) {
    return array_reduce($chunk, function($carry, $item) {
        $carry['user_id'] = $item['user_id'];
        $carry['total_amount'] += $item['amount'];
        return $carry;
    }, ['total_amount' => 0]);
}, $chunks);

// Output结果
print_r($result);

Output result:

 Array
(
    [0] => Array
        (
            [user_id] => 1
            [total_amount] => 250
        )
    [1] => Array
        (
            [user_id] => 2
            [total_amount] => 250
        )
    [2] => Array
        (
            [user_id] => 3
            [total_amount] => 300
        )
)

In this example, we first group the order data by 2 orders per group using array_chunk . We then aggregate each group of orders using array_reduce to calculate the total order amount for each user.

4. Complete example

If we encapsulate the above operation into a complete function, the code is as follows:

 function groupAndAggregateOrders($orders) {
    // according to用户 ID Grouping
    $chunks = array_chunk($orders, 2);  // Assume that there are at most two orders per group

    // 对每个Grouping计算用户的总订单金额
    return array_map(function($chunk) {
        return array_reduce($chunk, function($carry, $item) {
            $carry['user_id'] = $item['user_id'];
            $carry['total_amount'] += $item['amount'];
            return $carry;
        }, ['total_amount' => 0]);
    }, $chunks);
}

// Test data
$orders = [
    ['user_id' => 1, 'amount' => 100],
    ['user_id' => 2, 'amount' => 200],
    ['user_id' => 1, 'amount' => 150],
    ['user_id' => 3, 'amount' => 300],
    ['user_id' => 2, 'amount' => 50],
    ['user_id' => 1, 'amount' => 200],
];

// Calling functions
$result = groupAndAggregateOrders($orders);

// Output结果
print_r($result);

5. Summary

By combining array_chunk and array_reduce , we can easily group arrays and aggregate them. array_chunk allows us to split the data into multiple groups, while array_reduce allows us to perform custom aggregation calculations within each group. The combination of these two can greatly improve the readability of code and the ability to process complex data.