我从数组中得到错误的值。
$json = file_get_contents('http://onleague.stormrise.pt:8031/OnLeagueRest/resources/onleague/Utils/Countries');
$data = json_decode($json, TRUE);
$countries = array();
foreach($data['data'] as $item) {
$countries[] = $item['description'];
}
print_r($countries);
结果是:
Array ( [0] => g [1] => )
答案 0 :(得分:5)
您没有正确遍历该对象。
foreach($data['data']['item'] as $item) {
$countries[] = $item['description'];
}
如果您使用一些空格查看数据,可能会有所帮助。
{
"valid": true,
"id": "0",
"data": {
"@type": "genericObjectArray",
"item": [
{"id": "DE", "description": "Deutschland"},
{"id": "ES", "description": "España"},
{"id": "FR", "description": "France"},
{"id": "PT", "description": "Portugal"},
{"id": "UK", "description": "United Kingdom"},
{"id": "US", "description": "United States"}
]
}
}
答案 1 :(得分:1)
我遇到的问题非常疯狂,因为print_r在一个位置上获取值并通过索引获取另一个值(print_r在另一个位置显示的值)来获取该值,这对我帮助很大:How to convert an array to object in PHP? 。
我创建了一个stdClass,就像上面链接的相同问题上的另一个答案一样,并在
$obj->"X".index = value
获得类似
的内容 $obj->p1,$obj->p2,...
使用值后,用它来填充我的真实对象
$realobj1->myprop1 = $obj2->p1...
令人讨厌,但解决了我的问题