3

I have a JSON that I need to parse.

{
    "Room 251": {
        "calID": "igm4pfi6cc78ncvm5i3gv521snp0si82@import.calendar.google.com",
        "availMsg": "Open Computer Lab"
        },

    "Room 318": {
        "calID": "9duielvutvv2b8d52ikgf8793pbn43sk@import.calendar.google.com",
        "availMsg": "Open Computer Lab"
        },

    "Room 319 (Friends Room)": {
        "calID": "q5tj99a61g71eqcaboae6md0qahle2hv@import.calendar.google.com",
        "availMsg": "Available For Study"
        },

    "Room 323": {
        "calID": "josiglibstb75c88o4s4f2r3h4i3lagc@import.calendar.google.com",
        "availMsg": "Open Computer Lab"
        },

    "Room 513 (Voinovich Room)": {
        "calID": "anjv4nfcr0b00sttbjp6cse5l7j0mvbe@import.calendar.google.com",
        "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": "igm4pfi6cc78ncvm5i3gv521snp0si82@import.calendar.google.com",
        "availMsg": "Open Computer Lab"
        },

    "Room 318": {
        "calID": "9duielvutvv2b8d52ikgf8793pbn43sk@import.calendar.google.com",
        "availMsg": "Open Computer Lab"
        },

    "Room 319 (Friends Room)": {
        "calID": "q5tj99a61g71eqcaboae6md0qahle2hv@import.calendar.google.com",
        "availMsg": "Available For Study"
        },

    "Room 323": {
        "calID": "josiglibstb75c88o4s4f2r3h4i3lagc@import.calendar.google.com",
        "availMsg": "Open Computer Lab"
        },

    "Room 513 (Voinovich Room)": {
        "calID": "anjv4nfcr0b00sttbjp6cse5l7j0mvbe@import.calendar.google.com",
        "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