用PHP解析JSON数据

用PHP解析JSON数据

本文介绍了用PHP解析JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经多次解析JSON数据,但由于某种原因,在数据嵌套时找不到正确的语法。我试图解析从这个JSON的资产,但继续得到一个无效的参数提供foreach(),无论我尝试。

 3435:{
name:COLO-1014-SJ1,
nickname:US-SJC-004,
type:服务器,
location:San Jose:55 S Market,
assets:{
CPU:[
{
model :英特尔E3 1270
}
],
硬盘:[
{
型号:Western Digital 500GB RE4 ABYX SATA
$ b型号: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

{
型号:Super Talent 4GB DDR3 1333 ECC
},
{
型号: Super Talent 4GB DDR3 1333 ECC
}
],

期望它是沿线... $ / $>

  $ json = json_decode($ jsondata,true); 
$ b foreach($ json as $ item)
{
foreach($ item ['assets'] - > RAM as $ asset)
{
echo $ asset-> model;


解决方案

href =http://php.net/manual/fr/function.json-decode.php =nofollow> http://php.net/manual/fr/function.json-decode.php

第二个func arg用于assoc数组返回。你可以使用它,如果你喜欢在对象上操作assoc数组。



但是你实际上在你的循环中混合了数组和对象。

如果您保持arg TRUE ,请使用 $ item ['assets'] ['RAM']


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;
    }
解决方案

From php official documentation: http://php.net/manual/fr/function.json-decode.php

The 2nd func arg is for assoc array return. You can use it if you prefer to manipulate assoc array over object.

But you actually mix array and object in your loop.

If you keep the arg at TRUE, please use $item['assets']['RAM']

这篇关于用PHP解析JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:16