blahblah blahblah - 1 year ago 228
JSON Question

Symfony: iterate through json object to array

How can I iterate through each Json object parameters?

I receive Json object as input. How can I either to convert this object to array or iterate through each parameter?


"firstName": "Jane",
"lastName": "Dow",
"aboutMe": "Web developer"

In controller is it possible to do something like:

//$requestData - decoded json content
foreach ($requestData->data as $param){
//do smth with each param

In controller I am not able to decode json file to array, because I receive Json object as an input already.

Answer Source

You can use json_decode() to decode the JSON String to array or object. Like this,

$json_string="{  "firstName": "Jane",  "lastName": "Dow",  "aboutMe": "Web developer" }";

$json_array will be an array and you can iterate over it just like normally you do in PHP Array.

json_decode() accepts second parameter as boolean, which is false by default. If it is true json_decode() return an array otherwise it returns object.


You can iterate over PHP Object like this,

foreach ($requestData as $key => $value) {
    echo $key." =>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download