user3719363
user3719363

Reputation: 39

how to parse the json data using php I want to parse formattedAmount and currencyCode

    "deals": [
     {   
        "soldQuantity": 1000,
        "shippingAddressRequired": false,
    "options": [
        {
        "value": {
                    "formattedAmount": "$43.78",
                    "currencyCode": "USD",
                    "amount": 4378
                },
        },
    ],
},
]

I want to parse formattedAmount and currencyCode using php foreach loop

my code gives error :-Trying to get property of non-object

the code is

   $json = file_get_contents('../jsonfile/product.json');
   $json_string = json_decode($json);
   foreach($json_string->deals as $mydata)
   {
      foreach($mydata->options->value as $option)
  {                              
   echo $option->;
  }
   }

Upvotes: 0

Views: 69

Answers (2)

Yaniv
Yaniv

Reputation: 572

Don't do foreach($mydata->options->value as $option) because value is not array. Do:

foreach($mydata->options as $option) {
    echo $option->value->formattedAmount;
    echo $option->value->currencyCode;
    echo $option->value->amount;
}

Upvotes: 2

Jonathan M
Jonathan M

Reputation: 17451

Because the values of deals and options are arrays, you need to say:

foreach($mydata->options[0]->value as $option)

Your json is poorly formatted, by the way. Arrays should not have a comma after them, as your options array does. That alone will cause you problems.

A foreach is not really needed here, since there's only one value in the deals array, and only one in the options array.

Upvotes: 0

Related Questions