AAA
AAA

Reputation: 2450

Decoding a JSON object and echo a specific value?

I have a PHP page where I reference a JSON object that looks like this:

{
  "body": {
    "zip": "02110",
    "stores": [
      {
        "storeEmail": "[email protected]",
        "storeName": "Name",
        "city": "City",
        "Availability": {
          "123": {
            "Quote": "daily",
            "Display": "available",
          }
        },
      },

Each JSON object contains multiple "stores", above is one example.

I can currently echo the store name by using this:

echo "<br>".$phpArray->body->stores{0}->storeName;

How do I echo the value "123" from the sample JSON? I would also like to echo the quote as a separate variable. The value "123" will change for different searches. Any help would be greatly appreciated!

Upvotes: 0

Views: 85

Answers (2)

Patrick Webster
Patrick Webster

Reputation: 290

$phpArray = json_decode($json, true);
foreach($phpArray['body']['stores'] as $store) {
    echo $store['storeName'];
    foreach{$store['Availabilty'] as $avail => $info) { 
        echo $avail; // 123
        echo $info['Quote'];
    }
}

Upvotes: 1

&#212;rel
&#212;rel

Reputation: 7662

$b = json_decode($a); 
var_dump(key($b->body->stores{0}->Availability)); 
var_dump(reset($b->body->stores{0}->Availability)->Quote); 

or a loop for stores

foreach($b->body->stores as $store) {
    var_dump(key($store->Availability)); 
    var_dump(reset($store->Availability)->Quote);
}

Upvotes: 1

Related Questions