4

I've have this list of products in JSON that needs to be decoded:

"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"

After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.

Thanks!

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Kaltsoon
  • 325
  • 1
  • 3
  • 8
  • $decoded_json = json_decode($list);, then output the array as echo "
    "; print_r($decoded_json); echo "
    "; and paste the output here
    – sven Aug 27 '13 at 11:50

5 Answers5

11

To convert json to an array use

 json_decode($json, true);
Josh M
  • 982
  • 1
  • 7
  • 19
9

You can use json_decode() It will convert your json into array.

e.g,

$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array

Then you can loop array variable like,

foreach($json_array as $json){
   echo $json['key']; // you can access your key value like this if result is array
   echo $json->key; // you can access your key value like this if result is object
}
Anjana Silva
  • 8,353
  • 4
  • 51
  • 54
7

Try like following codes:

$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';

$array = json_decode($json_string);

foreach ($array as $value)
{
   echo $value->productId; // epIJp9
   echo $value->name; // Product A
}

Get Count

echo count($array); // 2
Bora
  • 10,529
  • 5
  • 43
  • 73
1

Did you check the manual ?

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

Or just find some duplicates ?

How to convert JSON string to array

Use GOOGLE.

json_decode($json, true);

Second parameter. If it is true, it will return array.

Community
  • 1
  • 1
m1k1o
  • 2,344
  • 16
  • 27
0

You can try the code at php fiddle online, works for me

 $list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';

$decoded_list = json_decode($list); 

echo count($decoded_list);
print_r($decoded_list);
sven
  • 775
  • 5
  • 14