stdClass Object and array how to using php
Asked Answered
N

3

5

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

Neology answered 1/3, 2011 at 15:52 Comment(0)
R
9

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;
Randirandie answered 1/3, 2011 at 16:0 Comment(0)
C
2

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

Contretemps answered 19/4, 2013 at 9:59 Comment(0)
O
0

change

$a1[] = $checkins['items'][$i]['venue']['id'];

changed to

$a1[] = $checkins->items[$i]->venue->id; 
Ophthalmoscopy answered 1/3, 2011 at 16:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.