Home >Backend Development >PHP Problem >How to sum json arrays in php
Method for summing json arrays in php: 1. Create a PHP sample file; 2. Define the variable $jsonArrayStr to store the provided JSON array and change it to a string type; 3. Use the "json_decode()" function Decode it into a PHP array for processing; 4. Use the array_reduce() function to iterate the calculated value and return the total result; 5. Echo output and print the result.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
The method for summing json arrays in PHP is:
Use PHP's built-in json_decode() function to decode it. Then use the array_reduce() function to sum the arrays.
The sample code is as follows:
<?php // Your JSON array as a string $jsonArrayStr = '[{"value": 10}, {"value": 20}, {"value": 30}]'; // Decode the JSON array into a PHP array $jsonArray = json_decode($jsonArrayStr, true); // Use array_reduce() function to sum up all values in the array $totalSum = array_reduce($jsonArray, function($carry, $item) { return $carry + $item['value']; }); echo $totalSum; // Output: 60 ?>
In the above example, the provided JSON array is first stored as a string in the $jsonArrayStr variable. Then use the json_decode() function to decode it into a PHP array for subsequent processing.
Next, we use the array_reduce() function, which accepts two parameters: the array to be processed and a callback function. The callback function uses the $carry parameter to store the value calculated in the previous iteration, and adds it to the current item's $item['value'] on each iteration, and finally returns the sum result.
Then, just output the result 60 to the screen.
The above is the detailed content of How to sum json arrays in php. For more information, please follow other related articles on the PHP Chinese website!