我还不清楚数组.我需要一些帮助 – 我有一些
JSON,我已经通过一些基本上解析JSON并且解码它的
PHP来运行它,如下所示:
- 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
- )
这实际上是继续的 – 但是 – 我的问题是stdClass对象部分.我需要能够在for循环中调用它,然后遍历每个部分(home,score,abbr,to等).我该怎么办?
您可以使用get_object_vars()获取对象属性的数组,或者使用json_decode($string,true)调用json_decode();获取关联数组.
例:
- <?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;
- }
- ?>
输出:
- 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