在PHP中解析Json字符串从数组获取值[重复]
This question already has an answer here:
- How can I parse a JSON file with PHP? 16 answers
{
"DeviceTicketInfo ": {
"UserId ": 27,
"Ticket ": 18005956,
"DevInfo ": "sunsoft-123456 "
},
"AvailableStations ": [{
"Id ": 2,
"No ": 2,
"Name ": "01-SUNSOFT "
}]
}
I want to echo only the UserId
from the above json
string in php
.
Please help
</div>
此问题已经存在 这里有一个答案: p>
-
如何用PHP解析JSON文件?
16 answers \ r
span>
li>
ul>
div>
{ “DeviceTicketInfo”:{\ n“UserId”:27, “Ticket”:18005956, “DevInfo”:“sunsoft-123456” }, “AvailableStations”:[{ “Id”:2, “否 “:2, ”名称“:”01-SUNSOFT“ }] } code> pre>
我想只回显
UserId 来自
php code>中的
json code>字符串。 p>
请帮助 p> div>
For any json
formatted strings, or array, you can simply use the json_encode
/json_decode
PHP built-in functions.
To decode that json just do something the json_decode()
function:
$jsonString = '{
"DeviceTicketInfo ": {
"UserId ": 27,
"Ticket ": 18005956,
"DevInfo ": "sunsoft-123456 "
},
"AvailableStations ": [{
"Id ": 2,
"No ": 2,
"Name ": "01-SUNSOFT "
}]
}';
$array = json_decode($jsonString, true);
This will return a 2-d array with key
=>value
pairs.
You'll need to convert the json
string
into a PHP object
before accessing its properties, json_decode()
is your friend here, i.e.:
$_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
You can also use true
as 2nd argument in json_decode($_json, true);
to converted the returned object
into an associative array
, then you can access the elements using:
$_json['DeviceTicketInfo']['UserId'];