問(wèn)題描述
我已多次解析 JSON 數(shù)據(jù),但由于某種原因,無(wú)法找到嵌套數(shù)據(jù)時(shí)要使用的正確語(yǔ)法.我正在嘗試從此 JSON 解析資產(chǎn)",但無(wú)論我嘗試什么,都會(huì)繼續(xù)獲得為 foreach() 提供的無(wú)效參數(shù).
I have parsed JSON data numerous times but for some reason cannot find the correct syntax to use when the data is nested. I am trying to parse the "assets" from this JSON but continue to get a invalid argument supplied foreach() regardless of what I try.
"3435":{
"name":"COLO-1014-SJ1",
"nickname":"US-SJC-004",
"type":"Colocated Server",
"location":"San Jose:55 S Market",
"assets":{
"CPU":[
{
"model":"Intel E3 1270"
}
],
"Hard Drives":[
{
"model":"Western Digital 500GB RE4 ABYX SATA"
},
{
"model":"Western Digital 500GB RE4 ABYX SATA"
},
{
"model":"Kingston 240GB SSD"
}
],
"RAM":[
{
"model":"Super Talent 4GB DDR3 1333 ECC"
},
{
"model":"Super Talent 4GB DDR3 1333 ECC"
},
{
"model":"Super Talent 4GB DDR3 1333 ECC"
},
{
"model":"Super Talent 4GB DDR3 1333 ECC"
}
],
我希望它類似于......
I would expect it to be something along the lines of...
$json = json_decode($jsondata, true);
foreach ($json as $item)
{
foreach ($item['assets']->RAM as $asset)
{
echo $asset->model;
}
推薦答案
來(lái)自php官方文檔:http://php.net/manual/fr/function.json-decode.php
第二個(gè) func arg 用于關(guān)聯(lián)數(shù)組返回.如果您更喜歡在對(duì)象上操作關(guān)聯(lián)數(shù)組,則可以使用它.
The 2nd func arg is for assoc array return. You can use it if you prefer to manipulate assoc array over object.
但你實(shí)際上在循環(huán)中混合了數(shù)組和對(duì)象.
But you actually mix array and object in your loop.
如果您將參數(shù)保持在 TRUE
,請(qǐng)使用 $item['assets']['RAM']
If you keep the arg at TRUE
, please use $item['assets']['RAM']
這篇關(guān)于用 PHP 解析 JSON 數(shù)據(jù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!