Reputation: 1680
I need to sum values of json object using PHP
json
{
"links": [
{
"source": 9887878787,
"target": 9999999993,
"value": 1
},
{
"source": 9999999993,
"target": 9887878787,
"value": 2
}
]
}
Want to Combine value of first and second object to get
desired output
{
"links": [
{
"source": 9887878787,
"target": 9999999993,
"value": 3
},
{
"source": 9999999993,
"target": 9887878787,
"value": 3
}
]
}
How can I achieve this without using javasript.I need php script for that?
Thank you a lot in advance.
Upvotes: 0
Views: 78
Reputation: 1792
Here is a way to do it :
$data = json_decode('{
"links": [
{
"source": 9887878787,
"target": 9999999993,
"value": 1
},
{
"source": 9999999993,
"target": 9887878787,
"value": 2
}
]
}');
$sum = 0;
foreach ($data->links as $link) {
$sum += $link->value;
}
foreach ($data->links as &$link) {
$link->value = $sum;
}
echo json_encode($data);
Hope this helps.
Upvotes: 1