PHP is a popular scripting language that is widely used for web development. Among them, arrays are an important feature of PHP, which can be used to store, process and operate data. In the actual development process, we often encounter situations where we need to sum the same fields in an array. This article will introduce how to use PHP to sum the same fields in an array.
1. Definition of array
In PHP, an array can be defined as a special variable that can store a group of related data items. Each data item in the array can be indexed and accessed through a unique index or key. There are two ways to define an array, one is to use the array() constructor, the other is to use square brackets [].
For example:
$arr1 = array('apple'=>3,'banana'=>2,'orange'=>4); $arr2 = ['apple'=>3,'banana'=>2,'orange'=>4];
The above two definitions have the same semantics, that is, an associative array is created in which each element has a string key. The following will take the first definition method as an example to explain.
2. Array traversal
Traversing an array is a basic operation for operating data items in an array. There are two ways to traverse arrays in PHP. One is to use a for loop to traverse, and the other is to foreach loop traverses.
For example, use a for loop to traverse the $arr1 array:
for($i=0;$i<count($arr1);$i++){ echo $arr1[$i]."<br>"; }
Use a foreach loop to traverse the $arr1 array:
foreach($arr1 as $k => $v){ echo "{$k}:{$v}<br>"; }
The above two traversal methods, the first one applies to indexes Array, the second one is suitable for associative array.
3. Method for summing the same fields in an array
To sum the same fields in an array, you need to traverse the array first, and then summarize based on the same fields. The specific implementation process is as follows:
1. Define a new array $sumArr to store the results of the sum of the same fields.
$sumArr = array();
2. Traverse the original array $arr1 and make a judgment on each data item.
foreach($arr1 as $key => $value){ if(isset($sumArr[$key])){ //如果$sumArr中已有$key,则将$value累加到$sumArr[$key]中 $sumArr[$key] += $value; }else{ //如果$sumArr中没有$key,直接将$value赋值给$sumArr[$key]。 $sumArr[$key] = $value; } }
3. Output the results.
foreach($sumArr as $k => $v){ echo "{$k}:{$v}<br>"; }
Summary
This article introduces how to use PHP to sum the same fields in an array. By traversing the array, first determine whether the same field has appeared. If it has appeared, the data of the same field will be accumulated. Otherwise, a new data item will be created. This method can be flexibly applied in development to achieve various data processing needs.
The above is the detailed content of How to sum the same fields in an array using PHP. For more information, please follow other related articles on the PHP Chinese website!