dre*_*ard 10 php arrays iteration json
我对数组还很新.我需要一些帮助 - 我有一些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
)
Run Code Online (Sandbox Code Playgroud)
这实际上一直在继续 - 但是 - 我的问题就是这个stdClass Object部分.我需要能够在for循环中调用它,然后遍历每个部分(home,score,abbr,to等).我该怎么做?
Wri*_*ken 21
您可以使用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;
}
?>
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28691 次 |
| 最近记录: |