简体   繁体   English

PHP/JSON - stdClass 对象

[英]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:我需要一些帮助 - 我有一些 JSON,我已经通过一些 PHP 运行它,基本上解析 JSON 并将其解码如下:

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.这实际上一直在继续 - 但是 - 我的问题是stdClass Object部分。 I need to be able to call this in a for loop and then iterate through each section (home, score, abbr, to, etc).我需要能够在 for 循环中调用它,然后遍历每个部分(home、score、abbr、to 等)。 How would I go about this?我该怎么办?

You can use get_object_vars() to get an array of the object's properties, or call json_decode() with json_decode($string,true);您可以使用get_object_vars()获取对象属性的数组,或使用json_decode($string,true);调用json_decode() 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

您可以使用foreach迭代stdClass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM