PHP解析JSON字符串并输出指定UserId字段值的实现方法求助
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

