-1
{
    "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

Sam
  • 2,856
  • 3
  • 18
  • 29

2 Answers2

1

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.

Sam
  • 2,856
  • 3
  • 18
  • 29
0

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'];

Ideone Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268