How to sum three-dimensional arrays in php

百草
Release: 2023-06-12 10:41:42
Original
912 people have browsed it

Method for summing three-dimensional arrays in php: 1. Create a php sample file; 2. Define a variable named "$total" to record the accumulated results; 3. Use a foreach loop to traverse separately Two-dimensional array and one-dimensional array, and then implement recursive summation through the "sumArray()" function, and accumulate the return value to "$total"; 4. Output the value of $total through echo.

How to sum three-dimensional arrays in php

The operating system of this tutorial: Windows 10 system, PHP8.1.3 version, DELL G3 computer.

How to sum three-dimensional arrays in php?

Suppose there is the following three-dimensional array:

$arr = [
    [
        [1, 2, 3],
        [4, 5, 6],
    ],
    [
        [7, 8, 9],
        [10, 11, 12],
    ]
];
Copy after login

Requires the sum of all values ​​in it, which can be achieved using recursive summation.

function sumArray($arr) {    
$total = 0;    
foreach ($arr as $value) {    
if (is_array($value)) {    
$total += sumArray($value);    
} else {    
$total += $value;    
}    
}    
return $total;    
}    
echo sumArray($arr); // 输出: 78
Copy after login

In the above code, we define a recursive function named `sumArray`, which receives an array as a parameter and returns the sum of all values.

The function first defines a variable named `$total` to record the accumulated results. Then iterate through each element in the array. If the current element is still an array, call the `sumArray` function recursively and accumulate the return value into `$total`. Otherwise, the value of the current element is directly accumulated into `$total`.

The final returned value of `$total` is the sum of all values ​​in the array.

It should be noted that during the recursive calling process, the function will continue to call itself until it traverses to the innermost array element, then jumps back to the previous level call, and continues to traverse the next element, gradually Return recursively until eventually the sum of the entire array is returned.

The above is the detailed content of How to sum three-dimensional arrays in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template