Home > OS >  Access JSON values in PHP (one part is working, other one not)
Access JSON values in PHP (one part is working, other one not)

Time:07-01

I have this JSON:

[
{
    "Ticket": {
        "TicketNo": 1920,
        "Creation": "21.03.2016 05:45:00",
        "FailureDescription": "Error 46",
    },
    "Measures": [
        {
            "StartTime": "2017-03-17T05:45:00",
            "Description": "Long description",
        }
    ]
},
{
    "Ticket": {
        "TicketNo": 1005,
...

and here is the code I use to display data:

$file = file_get_contents($remote_url, false, $context);
$myData = json_decode($file);

foreach($myData as $myItem) {
   echo "<tr><td>$myItem->TicketNo</td><td>CLOSED</td><td>$myItem->Creation</td><td>$myItem->FailureDescription</td></tr>";
   echo "<tr><th>Start</th><th>Measure</th></tr>";

   foreach ($myItem->Measures as $wm) {
      echo "<tr><td>$wm->StartTime</td><td>$wm->Description</td></tr>";
   }
}

Problem is, that the 'Ticket' part is not showing at all, but the 'Measures' part is working well. I think it's because of the missing [ ] after 'Ticket', but I'm desperate to make it work.

JSON is valid and var_dump($myData) returns all of the data. I've tried to decode the JSON with 'json_decode($file, true)' to get an array and use $mydata['Ticket']['TicketNo'] but it didn't work either. I've tried '$myData->Ticket' in the first foreach with no effect. I've also read all the offered similar questions here in SO, but I didn't find a solution. Thank you

CodePudding user response:

You have two errors here.

Firstly, you need to read the structure of the JSON carefully to see what to access. The JSON has:

  • An array [, which you are looping with foreach($myData as $myItem) {
  • Each item in that array, has two keys: "Ticket" and "Measures"; access them as $myItem->Ticket and $myItem->Measures
  • Each "Ticket" has the keys "TicketNo", "Creation", and "FailureDescription". Those are not keys of $myItem, they are sub-keys of $myItem->Ticket; in other words, $myItem->Ticket->TicketNo, $myItem->Ticket->Creation, and $myItem->Ticket->FailureDescription

Your second problem is that when you write $myItem->Ticket->TicketNo inside a double-quoted string, like "hello $myItem->Ticket->TicketNo world", PHP thinks you want the variable $myItem->Ticket followed by the literal text "->TicketNo world". To fix that, put the variable part in curly braces: "hello {$myItem->Ticket->TicketNo} world".

So the echo line should be:

echo "<tr><td>{$myItem->Ticket->TicketNo}</td><td>CLOSED</td><td>{$myItem->Ticket->Creation}</td><td>{$myItem->Ticket->FailureDescription}</td></tr>";
  • Related