Home  >  Article  >  Backend Development  >  How to sum json arrays in php

How to sum json arrays in php

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-06-07 10:33:251058browse

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.

How to sum json arrays in php

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 = &#39;[{"value": 10}, {"value": 20}, {"value": 30}]&#39;;
// 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[&#39;value&#39;];
});
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!

Statement:
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