PHP:如何解析stdClass对象?

时间:2013-05-05 00:12:35

标签: php stdclass

我正在尝试解析从SmartyStreets(它是一家地址验证公司)返回的这些数据。

以下是一个例子:

Array
(
    [0] => stdClass Object
        (
            [input_index] => 0
            [candidate_index] => 0
            [delivery_line_1] => 3785 Las Vegas Blvd S
            [last_line] => Las Vegas NV 89109-4333
            [delivery_point_barcode] => 891094333992
            [components] => stdClass Object
                (
                    [primary_number] => 3785
                    [street_name] => Las Vegas
                    [street_postdirection] => S
                    [street_suffix] => Blvd
                    [city_name] => Las Vegas
                    [state_abbreviation] => NV
                    [zipcode] => 89109
                    [plus4_code] => 4333
                    [delivery_point] => 99
                    [delivery_point_check_digit] => 2
                )

            [metadata] => stdClass Object
                (
                    [record_type] => H
                    [county_fips] => 32003
                    [county_name] => Clark
                    [carrier_route] => C024
                    [congressional_district] => 01
                    [building_default_indicator] => Y
                    [rdi] => Commercial
                    [latitude] => 36.10357
                    [longitude] => -115.17295
                    [precision] => Zip9
                )

            [analysis] => stdClass Object
                (
                    [dpv_match_code] => D
                    [dpv_footnotes] => AAN1
                    [dpv_cmra] => N
                    [dpv_vacant] => N
                    [active] => Y
                    [footnotes] => B#H#L#M#
                )

        )

)

我刚开始使用Objects,所以我很难理解它是如何工作的。从上面的print_r $结果输出,我正在尝试访问[delivery_line1],[city_name],[state_abbreviation],[zipcode]和[plus4_code]。

如何在PHP中访问此树?

我试过这个:

echo $result["delivery_line_1"];

但是这给出了“Undefined index:delivery_line_1”。

echo $result->delivery_line_1;

但是这给了“试图获得非对象的属性”。

我错过了什么?谢谢!

1 个答案:

答案 0 :(得分:6)

$result[0]->delivery_line_1;

$result是一个包含对象的数组。