Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stdClass Object and array how to using php

I'm trying to get the twelve ids that this structure shows:

stdClass Object
(
    [checkins] => stdClass Object
        (
            [count] => 12
            [items] => Array
                (
                    [0] => stdClass Object
                        (

                            [venue] => stdClass Object
                                (
                                    [id] => 4564654646456
                                    .
                                    .

I do:

$checkins = $fsObjUnAuth->get("/users/self/checkins");
$count = $checkins ->response->checkins->count;  // so I can  get 12

 for( $i = 0; $i < $count; $i ++)
  {
      $a1[] = $checkins['items'][$i]['venue']['id'];  //two tries
      $a2[] = $checkins ->response->checkins->items->$i->venue->id;
        echo $i; echo ": ";
        echo $a1;echo"<br>";
        echo $a2;echo"<br>"
  } 

But I get: Fatal error: Cannot use object of type stdClass as array in line..

Please can someone show me how to do this?

Thanks a lot

like image 958
user638009 Avatar asked Mar 01 '11 15:03

user638009


People also ask

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.

How do you create a stdClass object?

Creating stdClass Object php $obj= new stdClass(); $obj->name= 'W3schools'; $obj->extension= 'In'; var_dump($object); ?> Whenever you need a generic object instance in your program, you can use stdClass because when you cast any other type to an object, you will get an instance of stdClass.

How do you create an object in PHP?

Objects of a class is created using the new keyword.

How do you access the properties of an object in PHP?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!


2 Answers

You cannot access object members via the array subscript operator [].

You have to use the -> operator:

$x = new StdClass();

$x->member = 123;

In your case you'll have to use a mixture, since you have an object ($checkins) with a member ($items) which is an array, which contains additional objects.

$a1[] = $checkins->items[$i]->venue->id;
like image 124
meagar Avatar answered Oct 16 '22 23:10

meagar


Here is a simple solution to convert a stdClass Object in array in php with function get_object_vars

Look at : http://php.net/manual/fr/function.get-object-vars.php

Ex :

debug($array);
$var = get_object_vars($array);
debug($var);

Or replace debug by print_r

I'm use CakePHP framework

Cdt

like image 25
Breith Avatar answered Oct 17 '22 00:10

Breith