2

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?

Example:

 {
  "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.

2
  • you want to iterate over attribute? So firstname is the first eleement of the array, lastname the second etc? Commented Aug 11, 2016 at 8:32
  • Casting it to an array might work, like $array = (array) $requestData->data;. Commented Aug 11, 2016 at 8:37

1 Answer 1

4

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=json_decode($json_string,true);

$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.

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


You can iterate over PHP Object like this,

foreach ($requestData as $key => $value) {
    echo $key." =>";
    var_dump($value);
}
Sign up to request clarification or add additional context in comments.

4 Comments

That's the trick, I am not receiving Json file as an input, I am receiving decoded Json object. So I can't decode file to array
Do you have JSON string in the variable ?
No, only json object. Is it ok to encode it back to json string and decode it to array?
If it's a JSON object you can directly iterate over it like an array. See my updated answer.

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.