php中的Parse Json String从数组中获取值

时间:2018-04-27 14:56:29

标签: php json

{
    "DeviceTicketInfo ": {
        "UserId ": 27,
        "Ticket ": 18005956,
        "DevInfo ": "sunsoft-123456 "
    },
    "AvailableStations ": [{
        "Id ": 2,
        "No ": 2,
        "Name ": "01-SUNSOFT "
    }]
}

我想仅回复UserId中上述json字符串中的php

请帮忙

2 个答案:

答案 0 :(得分:1)

对于任何json格式化的字符串或数组,您只需使用json_encode / json_decode PHP内置函数。

要解码json,只需执行json_decode()函数:

$jsonString = '{
    "DeviceTicketInfo ": {
        "UserId ": 27,
        "Ticket ": 18005956,
        "DevInfo ": "sunsoft-123456 "
    },
    "AvailableStations ": [{
        "Id ": 2,
        "No ": 2,
        "Name ": "01-SUNSOFT "
    }]
}';

$array = json_decode($jsonString, true);

这将返回一个包含key => value对的二维数组。

答案 1 :(得分:0)

在访问其属性之前,您需要将json string转换为PHP object,此处json_decode()是您的朋友,即:

$_json = '{ "DeviceTicketInfo":{ "UserId":27, "Ticket ":18005956, "DevInfo ": "sunsoft-123456 "}, "AvailableStations ":[{ "Id ":2, "No ":2, "Name ": "01-SUNSOFT "}]}';
$_json = json_decode($_json);
print_r($_json->DeviceTicketInfo->UserId);
# 27

您还可以使用true作为json_decode($_json, true);中的第二个参数,将返回的object转换为关联array,然后您可以使用以下内容访问元素:

$_json['DeviceTicketInfo']['UserId'];

Ideone Demo