Reputation: 1018
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.
Upvotes: 2
Views: 2337
Reputation: 8012
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);
}
Upvotes: 4