我正在尝试获取某人所连接的蒸汽组的ID。这是json输出:
{
"response": {
"success": true,
"groups": [
{
"gid": "111"
},
{
"gid": "222"
},
{
"gid": "333"
},
{
"gid": "444"
},
{
"gid": "555"
}
]
}
}
我是通过以下方式尝试的:
$groupIDs = $reply['response']['groups'];
foreach ($groupIDs as $gID) {
// Do stuff
}
我收到以下错误,但我很难看到如何纠正错误。
Invalid argument supplied for foreach()
抱歉,我没说清楚。我已经在foreach()之前解码了它。
$reply = json_decode($reply, true);
答案 0 :(得分:1)
首先,你必须使用php函数json_decode解码json字符串。然后迭代对象,如下所示
$string = '{
"response": {
"success": true,
"groups": [
{
"gid": "111"
},
{
"gid": "222"
},
{
"gid": "333"
},
{
"gid": "444"
},
{
"gid": "555"
}
]
}
}';
$array = json_decode($string);
foreach($array->response->groups as $value ){
echo $value->gid;
echo "<br/>";
}
答案 1 :(得分:1)
http://php.net/manual/pt_BR/function.json-decode.php
尝试:
$response = json_decode($reply, true);
$groupIDs = $response['response']['groups'];
foreach ($groupIDs as $gID) {
// Do stuff
}
答案 2 :(得分:0)
使用json_decode($ response)cf doc
$rep = json_decode($response)
foreach ($rep->response->groups as $gID) {
// Do stuff
}
答案 3 :(得分:0)
$groups = $reply['response']->groups;
foreach ($groups as $group) {
print $group->gid;
}
在json中,每个{}
表示被解析为对象,每个[]
被解析为数组。