PHP recursive function to sum specifix value in all childs
I was facing an issue to sum all child values in an array and I just created a simple function to solve my issue. I'm sharing this for knowledge improvement.
$json = '{
"name": "ABC",
"subArr": [{
"name": "def",
"count": 10,
"subArr": [{
"name": "ghi",
"count": 5
}, {
"name": "jkl",
"count": 15,
"subArr": [{
"name": "mno",
"count": 5
}]
}]
}, {
"name": "pqr",
"count": 10,
"subArr": [{
"name": "stu",
"count": 5
}, {
"name": "vwx",
"count": 15,
"subArr": [{
"name": "yz",
"count": 5,
"subArr": [{
"name": "yz",
"count": 5,
"subArr": [{
"name": "yz",
"count": 5
}]
}]
}]
}]
}]
}';
My Answer:
function sumChildValues($arr, $key) {
$sum = 0;
foreach ($arr as $item) {
if (isset($item[$key])) {
$sum += $item[$key];
}
if (isset($item['subArr'])) {
$sum += sumChildValues($item['subArr'], $key);
}
}
return $sum;
}
$jsonArray = json_decode($json, true);
$totalCount = sumChildValues($jsonArray['subArr'], 'count');
echo "Total count of all child values: " . $totalCount; // Output: Total count of all child values: 80
Rate this post
4 of 5 based on 4513 votesComments