Current Location: Home> Latest Articles> How to Perform Efficient Sum Calculations in ThinkPHP

How to Perform Efficient Sum Calculations in ThinkPHP

gitbox 2025-06-28

Introduction

Sum calculations are a common requirement in development. ThinkPHP, as a popular PHP framework, provides various convenient methods for performing sum operations. This article will detail how to perform sum calculations in ThinkPHP to help developers quickly implement related functions.

Array Sum

One-dimensional Array Sum

For summing a one-dimensional array, ThinkPHP provides the sum() method. You can use PHP's array_sum() function to calculate the sum of the array. Here’s an example:

// Assume we have the following one-dimensional array
$arr = [1, 2, 3, 4];
// Use the sum() method to calculate the sum
$res = array_sum($arr);
dump($res); // Outputs 10

Two-dimensional Array Multi-column Sum

If you need to sum multiple columns in a two-dimensional array, you can use MySQL's SUM() function. Here's how to do it:

// Use MySQL's SUM() function for summing
$res = Db::name('user')
    ->where('status', 1)
    ->sum('field1+field2');
dump($res);

In this example, field1 and field2 are the columns to be summed.

Query Builder Sum

Simple Sum

ThinkPHP's query builder allows you to easily perform sum calculations using the sum() method. Here's a simple sum example:

// Simple sum
$res = Db::name('user')
    ->where('status', 1)
    ->sum('score');
dump($res);

In this example, 'score' is the column to be summed.

Grouped Sum

If you need to perform a grouped sum based on a column, you can use the group() method. Here's an example of a grouped sum:

// Grouped sum
$res = Db::name('user')
    ->where('status', 1)
    ->field('type, sum(score) as total_score')
    ->group('type')
    ->select();
dump($res);

In this example, 'type' is the column used for grouping, and 'total_score' is the alias for the sum result.

Conclusion

As demonstrated in this article, ThinkPHP provides a simple and flexible way to perform sum calculations. Whether you’re working with a one-dimensional array, performing multi-column sums with MySQL, or using the query builder for sum operations, ThinkPHP offers efficient solutions. Mastering these summing techniques can improve efficiency and simplify your code implementation in real-world development scenarios.