在PHP中解析JSON字符串以显示其内容

时间:2016-04-28 12:19:47

标签: php json

我试图使用json_decode 但我认为结果两端的[]与它有关。

我需要访问此JSON的某些部分。

在PHP中我做:

<?php
  $arr = json_decode($json, true);
  print $arr['ua']['rawUa']; 
?>

实际的JSON(来自这里)是:

[
  {
    "meta": {
      "name": "ua-parser",
      "repo": "https://github.com/tobie/ua-parser",
      "version": "0.3.5"
    },
    "ua": {
      "rawUa": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2718.0 Safari/537.36",
      "string": {
        "family": "Chrome",
        "major": "52",
        "minor": "0",
        "patch": "2718"
      },
      "family": "Chrome",
      "major": 52,
      "minor": 0,
      "patch": 2718,
      "device": {
      "family": "Other"
    }
  },
  "os": {
    "string": {
      "family": "Mac OS X",
      "major": "10",
      "minor": "11",
      "patch": "1",
      "patchMinor": null
    },
  "family": "Mac OS X",
  "major": "10",
  "minor": "11",
  "patch": "1"
  }
},
{
  "meta": {
    "name": "ua-parser-js",
    "repo": "https://github.com/faisalman/ua-parser-js",
    "version": ""
  }
},
{
  "meta": {
    "name": "platform.js",
    "repo": "https://github.com/bestiejs/platform.js/",
    "version": "1.3.0"
    },
    "ua": {
      "name": "Chrome",
      "version": "52.0.2718.0",
      "layout": "Blink"
    },
    "os": {
      "os": {
        "architecture": 32,
        "family": "OS X",
        "version": "10.11.1"
      }
    },
    "device": {
      "product": null,
      "manufacturer": null,
      "description": "Chrome 52.0.2718.0 on OS X 10.11.1"
    }
  }
]

5 个答案:

答案 0 :(得分:0)

尝试使用:

print $arr[0]['ua']['rawUa'];

答案 1 :(得分:0)

只需使用第一个索引为0.您的数组第一个索引以0开头。

$arr = json_decode($json, true);

echo $arr[0]['ua']['rawUa'];

答案 2 :(得分:0)

尝试这个你必须从索引零获取数据,检查尝试打印数组var_dump($arr);

$arr = json_decode($data, true);

print $arr[0]['ua']['rawUa']; 

答案 3 :(得分:0)

使用foreach循环来获取所有记录。

$arr = json_decode($json, true);

foreach($arr as $row)
{
    if(isset($row['ua']['rawUa'])
    {
         echo $row['ua']['rawUa'];
    }
}

单次录音使用array index [0]

print $arr[0]['ua']['rawUa']; 

答案 4 :(得分:0)

的var_dump($ ARR);

结果部分:

array (size=3)
  0 => 
    array (size=3)
      'meta' => 
        array (size=3)
          'name' => string 'ua-parser' (length=9)
          'repo' => string 'https://github.com/tobie/ua-parser' (length=34)
          'version' => string '0.3.5' (length=5)
      'ua' => 
        array (size=7)
          'rawUa' => string 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2718.0 Safari/537.36' (length=119)