0

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
    )

)
7
  • 2
    decode the json to array first $new_array = json_decode($price_array,true); then sum it Commented Aug 29, 2016 at 6:40
  • <?php $data =json_decode($json_variable,true);echo "<pre/>";print_r($data); now this printed array will let you know how to get desired data. Commented Aug 29, 2016 at 6:41
  • your json data is not valid php.fnlist.com/php/json_decode Commented Aug 29, 2016 at 6:47
  • your json data is not valid check:- jsonlint.com Commented Aug 29, 2016 at 6:48
  • @Anant it is not full json. Commented Aug 29, 2016 at 6:50

2 Answers 2

2

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"));
Sign up to request clarification or add additional context in comments.

3 Comments

his json data is not valid check:- jsonlint.com
I have uploaded what array looks like
In that case, just follow the second line. It should give you your desired result.
1

First of all your json data is not valid

but i give the steps .how to sum the price

1)Decode the json to array first

2)then extract the price column by array_column function

3)then sum it using array_sum function

<?php $data =json_decode($json_variable,true);echo "<pre/>";print_r($data);

$price = array_column($data, "price"); 

echo $total_amount = array_sum($price);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.