You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP解析JSON字符串并输出指定UserId字段值的实现方法求助

Extract UserId from JSON in PHP

No problem, let's walk through how to get just the UserId value from your JSON string in PHP. The main steps are parsing the JSON into a usable PHP structure and then accessing the specific field—just note that your JSON keys have trailing spaces, which we need to account for when accessing them.

Using Associative Arrays

This approach converts the JSON into a PHP associative array, which you can access using key strings (including those trailing spaces):

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

// Parse JSON into an associative array (second parameter true enables this)
$parsedData = json_decode($jsonString, true);

// Check if parsing was successful
if ($parsedData === null) {
    echo "Failed to parse JSON: " . json_last_error_msg();
} else {
    // Access the UserId field (note the trailing spaces in the keys)
    $userId = $parsedData['DeviceTicketInfo ']['UserId '];
    // Output the value
    echo $userId; // Will print 27
}

Using PHP Objects

Alternatively, you can parse the JSON into a PHP object and access the fields using arrow notation. Since the keys have spaces, we'll use curly braces to wrap the key names:

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

// Parse JSON into a PHP object (default behavior of json_decode)
$parsedData = json_decode($jsonString);

// Check if parsing was successful
if ($parsedData === null) {
    echo "Failed to parse JSON: " . json_last_error_msg();
} else {
    // Access the UserId field using object notation with curly braces for spaced keys
    $userId = $parsedData->{'DeviceTicketInfo '}->{'UserId '};
    // Output the value
    echo $userId; // Will print 27
}

Important! The trailing spaces in your JSON keys (like "DeviceTicketInfo " instead of "DeviceTicketInfo") are easy to miss—if you omit those spaces when accessing the fields, you'll get an undefined index/property error. Make sure your key strings match exactly what's in the JSON.

内容的提问来源于stack exchange,提问作者user3053458

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:08:19