遍历PHP中的结构

时间:2011-04-28 06:49:46

标签: php

我有以下结构:

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
                )

        )

)

正如你所看到的性别&生日是不同大小的数组。由于性别和生日的大小不同,我不知道如何遍历上述结构。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

为什么不单独访问这些值?就像您使用nameemailpassword完成可能一样。

$o成为JSON,然后执行以下操作:

$data = &$o['signupbasic'][0];

$genderObj   = $data['gender'];
$birthdayObj = $data['birthday'];

我不太确定你要完成什么,你能发布一些PHP代码吗?

答案 1 :(得分:1)

我不知道我是否明白了你的意思,但它会是这样的吗?

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";
}

假设$ json是json_decode调用的返回值。

答案 2 :(得分:0)

要让php理解json,它需要采用特殊格式

{
    "property1": "value1",
    "property2": "value2",
    "property3": "value3",
    "property4": "value4"
}

在php.net json_decode()函数

上查看更好的explenation