1 json_decode方法

在PHP中使用json_decode方法解析json字符串,json_decode方法如下。

语法

mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

参数

  • json_string: 待解码的 JSON 字符串,必须是 UTF-8 编码数据
  • assoc: 当该参数为 TRUE 时,将返回数组,FALSE 时返回对象
  • depth: 整数类型的参数,它指定递归深度
  • options: 二进制掩码,目前只支持 JSON_BIGINT_AS_STRING

2 使用json_decode方法解析json

假设有如下json字符串

{
    "name": "Monty",
    "email": "xxx@qq.com",
    "age": 77,
    "countries": [
        {"name": "Spain", "year": 1982},
        {"name": "Australia", "year": 1996},
        {"name": "Germany", "year": 1987}
    ]
}

可使用以下代码解析json,这里我们将第二个参数assoc设置为false,则返回一个对象

<?php
    $json = json_decode($json_str, false);
    $name = $json->name;
    $email = $json->email;
    $age = $json->age;
    $countries = $json->countries;
    foreach($countries as $country)
    {
        $country_name = $country->name;
        $country_year = $country->year;
    }
?>

如果我们将第二个参数assoc设置为true,则返回一个数组,则相应的解析代码为

<?php
    $json = json_decode($json_str, false);
    $name = $json['name'];
    $email = $json['email'];
    $age = $json['age'];
    $countries = $json['countries'];
    foreach($countries as $country)
    {
        $country_name = $country['name'];
        $country_year = $country['year'];
    }
?>