ayasocool
ayasocool

Reputation: 157

How to retrieve JSON array value to PHP?

I am having a hard time getting the value of an array in JSON to php.

Here is the JSON format I'm trying to retrieve:

{
 "products": [
  {
   "product_id": 18647,
   "model_code": "CVADA-M702-Black-2GEN"
  }
  {
   "product_id": 14343,
   "model_code": "CDEP-Q123-Blue-3GEN"
  }
 ]
}

and I'm trying to retrieve it like this but to no avail:

$response = json_decode($json_response, true);
        foreach($response as $res)
        {
            print $res->products->product_id;
        }

It works though if I'm only trying to input a singl output:

$response = json_decode($json_response, true);
print $response['products'][0]['product_id'];

So, can anyone help me how to properly retrieve JSON value to php?

Upvotes: 0

Views: 122

Answers (3)

Kamlesh Suthar
Kamlesh Suthar

Reputation: 172

Try this,

$response = json_decode('{
 "products": [
  {
   "product_id": 18647,
   "model_code": "CVADA-M702-Black-2GEN"
  },
  {
   "product_id": 14343,
   "model_code": "CDEP-Q123-Blue-3GEN"
  }
 ]
}');

foreach ($response->products as $res) {
    echo $res->product_id;
}

Upvotes: 1

Toretto
Toretto

Reputation: 4711

The JSON data you have missed the , between the two array. It should be

{
 "products": [
  {
   "product_id": 18647,
   "model_code": "CVADA-M702-Black-2GEN"
  },
  {
   "product_id": 14343,
   "model_code": "CDEP-Q123-Blue-3GEN"
  }
 ]
}

and another problem is you are accessing the array as an object , as you are decoding the JSON data as below it returns an array :

$response = json_decode($json_response, true);

it will return array.

$response = json_decode($ds, true);

try accessing value as below:

foreach($response['products'] as $res)
{
    print $res['product_id'];
}

for more detail check out the first example provided here :

http://php.net/manual/en/function.json-decode.php

Upvotes: 2

Tushar
Tushar

Reputation: 616

Your JSON format code has an small error, there should be ',' after following section.

 {    
    "product_id": 18647,   
    "model_code": "CVADA-M702-Black-2GEN"  
 },

Please check following code:

{
 "products": [
  {
   "product_id": 18647,
   "model_code": "CVADA-M702-Black-2GEN"
  },
  {
   "product_id": 14343,
   "model_code": "CDEP-Q123-Blue-3GEN"
  }
 ]
}

You can also check your JSON code on http://json.parser.online.fr/

Upvotes: 2

Related Questions