3

I have a JSON that I need to parse.

{
    "Room 251": {
        "calID": "[email protected]",
        "availMsg": "Open Computer Lab"
        },

    "Room 318": {
        "calID": "[email protected]",
        "availMsg": "Open Computer Lab"
        },

    "Room 319 (Friends Room)": {
        "calID": "[email protected]",
        "availMsg": "Available For Study"
        },

    "Room 323": {
        "calID": "[email protected]",
        "availMsg": "Open Computer Lab"
        },

    "Room 513 (Voinovich Room)": {
        "calID": "[email protected]",
        "availMsg": "Available For Study"
        }
}

I need to obtain the room name, the calID, and the available message. What would be the best way to go about doing this in PHP/Laravel?

Zach Tackett
  • 564
  • 3
  • 9
  • 25

2 Answers2

12

You can use json_decode to parse a json data.

mixed json_decode ( string $json [, bool $assoc ] )

For example:

$rooms = json_decode($yourJsonHere, true);

var_dump($rooms);

foreach($rooms as $name => $data) {
    var_dump($name, $data['calID'], $data['availMsg']); // $name is the Name of Room
}
Lucas Martins
  • 508
  • 6
  • 9
1

You can do something like that :

<?php
$json = '
{
    "Room 251": {
        "calID": "[email protected]",
        "availMsg": "Open Computer Lab"
        },

    "Room 318": {
        "calID": "[email protected]",
        "availMsg": "Open Computer Lab"
        },

    "Room 319 (Friends Room)": {
        "calID": "[email protected]",
        "availMsg": "Available For Study"
        },

    "Room 323": {
        "calID": "[email protected]",
        "availMsg": "Open Computer Lab"
        },

    "Room 513 (Voinovich Room)": {
        "calID": "[email protected]",
        "availMsg": "Available For Study"
        }
}';
foreach(json_decode($json) as $room_name => $room){
  echo $room_name.'<br/>'; // output the room name, for instead "Room 251"
  echo $room->calID.'<br/>'; // output the room calID
  echo $room->availMsg.'<br/>'; // output the room availMsg
}

 ?>
Vincent G
  • 8,547
  • 1
  • 18
  • 36