PHP/JSON - stdClass Object(PHP/JSON - 标准类对象)
问题描述
我对数组还是很陌生.我需要一些帮助 - 我有一些 JSON,我已经通过一些 PHP 运行它,基本上解析 JSON 并将其解码如下:
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
)
这实际上一直在继续 - 但是 - 我的问题是 stdClass Object
部分.我需要能够在 for 循环中调用它,然后遍历每个部分(home、score、abbr、to 等).我该怎么办?
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?
推荐答案
你可以使用 get_object_vars()
来获取对象属性的数组,或者调用 json_decode()
用 json_decode($string,true);
得到一个关联数组.
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.
示例:
<?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
这篇关于PHP/JSON - 标准类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP/JSON - 标准类对象
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Laravel 仓库 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01