Traversing a structure in PHP
I have the following structure:
Array
(
[signupbasic] => Array
(
[0] => Array
(
[name] => Enter your first name开发者_运维百科 or username
[email] => Enter your email address
[password] => Enter your password
[phone] => Enter your mobile number
[message1] => A text will be send to your phone - reply to validate
[gender] => Array
(
[label] => Gender
[values] => Array
(
[0] => Array
(
[Female] => 1
)
[1] => Array
(
[Male] => 2
)
)
)
[birthday] => Array
(
[label] => Date of birth
[values] => date
)
[message2] => By clicking on "Continue" below you agree to Terms of Service and Privacy Policy
)
)
)
As you can see Gender & Birthday are arrays of different sizes. I am not getting how can I traverse the above structure due to the varying size of Gender and Birthday.
How can I achieve this?
Why don't you just access those values separately? Just like you've probably done with name
, email
and password
.
Let $o
be the JSON and then do something along the lines of this:
$data = &$o['signupbasic'][0];
$genderObj = $data['gender'];
$birthdayObj = $data['birthday'];
I'm not quite sure what you're trying to accomplish, could you post some PHP code?
I don't know if I got what you meant, but would it be something like this ?
foreach($json['signupbasic'][0]['gender']['values'] as $genderValue) {
foreach($genderValue as $genderKey => $genderSubVal) {
echo $genderKey." ".$genderSubVal."\n\r";
}
}
foreach($json['signupbasic'][0]['birthday'] as $bdKey => $bdValue) {
echo $bdKey." ".$bdValue."\n\r";
}
Assuming $json is the return value of your json_decode call.
For php to understanding json, it needs to be in a special format
{
"property1": "value1",
"property2": "value2",
"property3": "value3",
"property4": "value4"
}
see a better explenation on php.net json_decode() function
精彩评论