Foreach item JSON 在 PHP 中解码?
Foreach item JSON decode in PHP?
我正在尝试做一些CS: Global Offensive 库存列表以供个人体验。现在我不知道应该如何显示库存中的所有项目。
库存JSON
{
"success":true,
"rgInventory":{
"1847345369":{
"id":"1847345369",
"classid":"638241994",
"instanceid":"188530139",
"amount":"1","pos":1
},
"1844330224":{
"id":"1844330224",
"classid":"469444104",
"instanceid":"0",
"amount":"1","pos":2
}
}
}
所以当我想要第一个项目的 id 时,我必须使用这个
$item = $parsed_json->{'rgInventory'}->{'1847345369'}->id;
但是在 json 解析中使用 itemid 是愚蠢的。我怎样才能让它列出所有项目的 ID?
使用数组而不是对象。
"rgInventory":[
{ "id":"1847345369", ...},
{ "id":"1844330224", ...}
]
然后用index获取([0]
等等)
使用 foreach()
循环。
<?php
$items = array();
foreach($parsed_json->{'rgInventory'} as $key => $obj) {
// $key now holds '1844330224' etc
$items[] = $obj->id; // or re-use $key here ;-)
}
?>
我正在尝试做一些CS: Global Offensive 库存列表以供个人体验。现在我不知道应该如何显示库存中的所有项目。
库存JSON
{
"success":true,
"rgInventory":{
"1847345369":{
"id":"1847345369",
"classid":"638241994",
"instanceid":"188530139",
"amount":"1","pos":1
},
"1844330224":{
"id":"1844330224",
"classid":"469444104",
"instanceid":"0",
"amount":"1","pos":2
}
}
}
所以当我想要第一个项目的 id 时,我必须使用这个
$item = $parsed_json->{'rgInventory'}->{'1847345369'}->id;
但是在 json 解析中使用 itemid 是愚蠢的。我怎样才能让它列出所有项目的 ID?
使用数组而不是对象。
"rgInventory":[
{ "id":"1847345369", ...},
{ "id":"1844330224", ...}
]
然后用index获取([0]
等等)
使用 foreach()
循环。
<?php
$items = array();
foreach($parsed_json->{'rgInventory'} as $key => $obj) {
// $key now holds '1844330224' etc
$items[] = $obj->id; // or re-use $key here ;-)
}
?>