Foreach循环数组和stdclass对象,获取值

时间:2012-03-21 03:24:44

标签: php arrays object foreach

我试图使用foreach达到一定的价值(我认为这是最好的方式,性能方面,如知道的那样)

[businesses] => Array
        (
            [0] => stdClass Object
                (
                    [rating] => 4
                    [location] => stdClass Object
                        (
                            [city] => Claremont
                            [display_address] => Array
                                (
                                    [0] => 580 W First St
                                    [1] => Claremont, CA 91711
                                )

                            [geo_accuracy] => 8
                            [postal_code] => 91711
                            [country_code] => US
                            [address] => Array
                                (
                                    [0] => 580 W First St
                                )

                            [coordinate] => stdClass Object
                                (
                                    [latitude] => 34.094112
                                    [longitude] => -117.7250746
                                )
                        )

                )
)

我试图获得经度和经度。但请记住,我将拥有的不只是[0] => stdClass Object。会有多个号码。我知道我可以做一些像$ response-> business [0] - > location或某种类型的东西,但只获得0密钥,我需要能够预先获得密钥。

有人可以帮我做一个关于此的事吗?

例如我到目前为止这样做......

foreach($response->businesses->location as $llk=>$coordinate){

    if($llk === "coordinate"){

        $selected_lat = $coordinate->latitude;
        $selected_lng = $coordinate->longitude;
    }
}

到目前为止它给了我错误。

谢谢!

3 个答案:

答案 0 :(得分:2)

以下可能正是您所寻找的:

foreach($response->businesses as $business) {
    if(!empty($business->location->coordinate)) {
       $coord = $business->location->coordinate;
       $selected_lat = $coord->latitude;
       $selected_long = $coord->longitude;
    }
}

答案 1 :(得分:1)

试试这个:

foreach ($response->businesses as $business) {
    $selected_lat = $business->location->coordinate->latitude;
    $selected_lng = $business->location->coordinate->longitude;
}

答案 2 :(得分:0)

您可能不需要foreach循环,只需使用简单的数组迭代来浏览顶级stdClass对象,然后使用解除引用来获取每个经度/纬度对。

for($i = 0; $i < count($response->businesses); $i++)
{
    $coords = $response->businesses[$i]->location->coordinate;
    $long = $coords->longitude;
    $lat = $coords->latitude;
}

这应该是我能说的。