Garg Garg - 3 months ago 11
JSON Question

Extracting value(s) from json array with php

My cart store orders in json_encode array into database. Is it possible to extract the total price from this array.. If there are 4 products I want to extract sum of all five prices?

Here is example of the array

{"73":{
"title":"Test",
"description":"",
"quantity":1,
"image":"",
"price":90},
"66":{
"title":"Title",
"description":"",
"quantity":1,
"image":"",
"price":80},
"shipping":{"
quantity":1,
"image":"",
"description":"",
"title":"Free Delivery",
"price":0
}
}


I want to extract all
price
fields and shwo the sum of them on the page.

edit: This is the array which I get

Array
(
[7] => Array
(
[title] => Test
[description] => Test
[quantity] => 1
[image] =>
[price] => 2
)

[6] => Array
(
[title] => Test
[description] => Test
[quantity] => 1
[image] =>
[price] => 12
)

[shipping] => Array
(
[quantity] => 1
[image] =>
[description] =>
[title] =>
[price] => 51
)

)

Answer

This is a JSON. It needs to be converted to array first.

And then, you can use array function array_column() to retrieve all "price" values and apply array_sum() to calculate the total price on this array.

// Assuming $data is the JSON.

$data  = json_decode($data, true); 
$price = array_sum(array_column($data, "price"));