Cómo acceder a los datos en la matriz de objetos estándar anidados en PHP

I need to access the data: 'hotelID', 'name', 'address1','city' etc. I have the following Std Object array ($the_obj) in PHP that contains the following data:

object(stdClass)[1]
  public 'HotelListResponse' => 
    object(stdClass)[2]
      public 'customerSessionId' => string '0ABAAA87-6BDD-6F91-4292-7F90AF49146E' (length=36)
      public 'numberOfRoomsRequested' => int 0
      public 'moreResultsAvailable' => boolean false
      public 'HotelList' => 
        object(stdClass)[3]
          public '@size' => string '227' (length=3)
          public '@activePropertyCount' => string '227' (length=3)
          public 'HotelSummary' => 
            array (size=227)
             0 =>
              object(stdClass)[4]
              public 'hotelId' => 112304 
              public 'name' => La Quinta Inn and Suites Seattle Downtown 
              public 'address1' => 2224 8th Ave 
              public 'city' => Seattle 
              public 'stateProvinceCode' => WA 
              public 'postalCode' => 98121 
              public 'countryCode' => US 
              public 'airportCode' => SEA 
              public 'propertyCategory' => 1 
              public 'hotelRating' => 2.5

I have tried the following for lets say to access the 'name':

echo $the_obj->HotelListResponse->HotelList->HotelSummary[0]->name;

Also I have tried to print each key and value pairs by using foreach loop but I keep on getting errors. Here is what I tried:

foreach ($the_obj->HotelListResponse->HotelList->HotelSummary[0] as $key => $value){
    echo $key.' : '.$value.'<br />';
}

Aquí están los errores que me sale:

  • Tratar de obtener la propiedad de no-objeto
  • Advertencia: argumento no válido proporcionado para foreach ()

preguntado el 27 de noviembre de 13 a las 06:11

Did you test step by step? For example: $the_obj->HotelListResponse; Siguiente $the_obj->HotelListResponse->HotelList; etc.. and find out where the problem is... -

It seems like it's actual data structure & structure on screen mismatch. Most common reason - you've dumped another data, while accessed something else. Are you sure that's var_dump($the_obj)? (output is different from it. try to do this var_dump) -

@GeorgeGarchagudashvili yes I did test it out step by step, the only deep I can access is: $the_obj->HotelListResponse->customerSessionId (in fact the public members of the HotelListResponse are all accessible ). If I go further more deeper, then I get an error -

I have also dumped the variables to see the stored data, but the var_dump only displays the data up to 3 nested object arrays and further it shows it by '...' (that the data is continued) -

One way to look deeper in this problem would be to serialize that object save to file and post link here, so we could examine object itself. If you can -

3 Respuestas

Thank you everyone for answering, I have figured out the way to access the 'hotelID', 'name' and all other keys and value pairs in the deepest nest of the array.

I converted the Std Object array to an associative array, then I accessed each of the value by using the foreach loop:

foreach ($the_obj["HotelListResponse"]["HotelList"]["HotelSummary"] as $value){
echo $value["hotelId"];
echo $value["name"];

//and all other values can be accessed
}

To access both (Keys as well as values):

foreach ($the_obj["HotelListResponse"]["HotelList"]["HotelSummary"] as $key=>$value){
    echo $key.'=>'.$value["hotelId"];
    echo $key.'=>'.$value["name"];

    //and all other keys as well as values can be accessed
    }

respondido 27 nov., 13:07

@GeorgeGarchagudashvili Thanks buddy :P :):) - Jade

Regarding to @Satya's answer I'd like to show simpler way for Object to array conversion, by using json funciones:

$obj = ...
$tmp = json_encode($obj);
$objToArray = json_decode($tmp,true);

This way you can easily access array items. First you can dump structure...

respondido 27 nov., 13:06

prueba algo como esto:

 $p=objectToArray($result);
recurse($p);
}

function objectToArray( $object )
    {
        if( !is_object( $object ) && !is_array( $object ) )
        {
            return $object;
        }
        if( is_object( $object ) )
        {
            $object = get_object_vars( $object );
        }
        return array_map( 'objectToArray', $object );
    }
function recurse ($array)
{
    //statements
    foreach ($array as $key => $value)
    {
        # code...
        if( is_array( $value ) )
        {   
          recurse( $value );
        }
        else
        {   $v=$value;
            $v=str_replace("&rsquo;",'\'',strip_tags($v));
            $v=str_replace("&ndash;",'-',$v);
            $v=str_replace("&lsquo;",'\'',strip_tags($v));
            $v=str_replace("&ldquo;",'"',strip_tags($v));
            $v=str_replace("&rdquo;",'"',strip_tags($v));
            $v=str_replace("&#8211;",'-',strip_tags($v));
            $v=str_replace("&#8217;",'\'',strip_tags($v));
            $v=str_replace("&#39;",'\'',strip_tags($v));
            $v=str_replace("&nbsp;",'',strip_tags($v));
            $v=html_entity_decode($v);
            $v=str_replace("&",' and ',$v);

        $v =  preg_replace('/\s+/', ' ', $v);
            if($key=="image")
            {
                if(strlen($v)==0)
                {
                    echo '<'.$key .'>NA</'.$key.'>';
                }
                else 
                {
                echo '<'.$key .'>'. trim($v)  .'</'.$key.'>';
                }
            }
            }
  }
}

respondido 27 nov., 13:07

removed ereg_Replace , try and let me know please - Satya

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.