phparraysobjectmultidimensional-array

How to access data in an array of objects containing arrays of objects?


I'm struggling with displaying the country_name, country_prefix followed by the city_name and city_prefix to display in PHP

Array (
    [0] => stdClass Object
        (
            [country_name] => Russian Federation
            [country_prefix] => 7
            [country_iso] => RU 
            [cities] => Array
                (
                    [0] => stdClass Object
                        (
                            [city_id] => 107
                            [city_name] => Moscow
                            [city_prefix] => 495
                            [city_nxx_prefix] => 
                            [setup] => 0
                            [monthly] => 60.9
                            [isavailable] => 1
                            [islnrrequired] => 0
                        )
                    ...

This above returns the $results array and I'm currently using something like this but have tried many iterations.

echo '<br />Results: <br />';
foreach ($result as $countries => $country) {
    foreach ($country as $details => $value) {
        echo $value . "<br/>";
    }
}

Solution

  • Try this:

    foreach($results as $country){
        // country name in $country->country_name
        foreach($country->cities as $city){
            echo $city->city_name.'<br/>';
        }
    }
    

    As you've been told in comments, you have an array of objects. You can iterate it with foreach, but then you should access its properties using the proper syntax (->)