Kaltsoon
Kaltsoon

Reputation: 325

How to loop through this json decoded data in PHP?

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!

Upvotes: 4

Views: 35795

Answers (5)

Bora
Bora

Reputation: 10717

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

Upvotes: 7

user2064468
user2064468

Reputation:

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
}

Upvotes: 9

sven
sven

Reputation: 785

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);

Upvotes: 0

m1k1o
m1k1o

Reputation: 2364

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.

Upvotes: 1

Josh M
Josh M

Reputation: 992

To convert json to an array use

 json_decode($json, true);

Upvotes: 11

Related Questions