Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/JSON - stdClass Object

I'm pretty new to arrays still. I need some help - I have some JSON, and I've run it through some PHP that basically parses the JSON and decodes it as follows:

stdClass Object
(
    [2010091907] => stdClass Object
        (
        [home] => stdClass Object
            (
                [score] => stdClass Object
                    (
                        [1] => 7
                        [2] => 17
                        [3] => 10
                        [4] => 7
                        [5] => 0
                        [T] => 41
                    )

                [abbr] => ATL
                [to] => 2
            )

This actually goes on and on - BUT - my problem is the stdClass Object part. I need to be able to call this in a for loop and then iterate through each section (home, score, abbr, to, etc). How would I go about this?

like image 814
drewrockshard Avatar asked Sep 20 '10 18:09

drewrockshard


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.


1 Answers

You can use get_object_vars() to get an array of the object's properties, or call json_decode() with json_decode($string,true); to get an associative array.


Example:

<?php
$foo = array('123456' =>
 array('bar' =>
        array('foo'=>1,'bar'=>2)));


//as object
var_dump($opt1 = json_decode(json_encode($foo)));

echo $opt1->{'123456'}->bar->foo;

foreach(get_object_vars($opt1->{'123456'}->bar) as $key => $value){
    echo $key.':'.$value.PHP_EOL;
}

//as array
var_dump($opt2 = json_decode(json_encode($foo),true));

echo $opt2['123456']['bar']['foo'];

foreach($opt2['123456']['bar'] as $key => $value){
    echo $key.':'.$value.PHP_EOL;
}
?>

Output:

object(stdClass)#1 (1) {
  ["123456"]=>
  object(stdClass)#2 (1) {
    ["bar"]=>
    object(stdClass)#3 (2) {
      ["foo"]=>
      int(1)
      ["bar"]=>
      int(2)
    }
  }
}
1
foo:1
bar:2

array(1) {
  [123456]=>
  array(1) {
    ["bar"]=>
    array(2) {
      ["foo"]=>
      int(1)
      ["bar"]=>
      int(2)
    }
  }
}
1
foo:1
bar:2
like image 105
Wrikken Avatar answered Nov 10 '22 01:11

Wrikken