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!

1
  • $decoded_json = json_decode($list);, then output the array as echo "<pre>"; print_r($decoded_json); echo "</pre>"; and paste the output here Commented Aug 27, 2013 at 11:50

5 Answers 5

11

To convert json to an array use

 json_decode($json, true);
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

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

Comments

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.

1 Comment

If you wish to vote to close a duplicate, please do not do so via an answer.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.