我对数组还是很陌生的。我需要一些帮助-我有一些JSON,并且已经通过一些PHP对其进行了运行,这些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
)
实际上,这种情况一直持续发生-但是-我的问题是
stdClass Object
部分。我需要能够在for循环中调用此函数,然后遍历每个部分(主页,得分,缩写,到等)。我将如何处理? 最佳答案
您可以使用get_object_vars()
来获取对象属性的数组,或者使用json_decode()
调用json_decode($string,true);
来获取关联数组。
示例:
<?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