DSmith
DSmith

Reputation: 137

parse json and display with php

I am having trouble parsing this data set that I have posted at pastebin here http://pastebin.com/TmZGw92j

I can step into it as far as routings but then can not go any further for some reason. Here are my vars that I have set up:

$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $airTicketListResponse->routings;
$trips = $routings->trips;
$segments = $trips->segments;

I can print_r($routings) but when I try to print_r($segments) I get nothing returned. I would like to pull items from routings and segments.

here is my current foreach loop that craps out at trips.

foreach($routings as $item){
    echo '<span style="font-weight:bold;">Airline - '.$item->mainAirlineName.' Price - '.$item->adultBasePrice.'</span><br />'.$item->trips->segments->departureAirportCode.' '.$item->trips->segments->departureTime.'<br /><br />';

    }

Upvotes: 1

Views: 127

Answers (2)

Spudley
Spudley

Reputation: 168853

The trips and segments elements are arrays of objects, not a single object.

So you need to reference the array element [0] which part of the structure.

$trips = $routings[0]->trips;
$segments = $trips[0]->segments;

Note, that there appear to be two trips, you'll also need $trips[1]->segments if you want all the segments.

More likely, you'll be wanting to use foreach() loops to read them, rather than directly referencing the array keys.

Something like this?

foreach($routings as $routing) {
    $trips = $routing->trips;
    .... do something here with $trips? ....
    foreach($trips as $trip) {
         $segments = $trip->segments;
         .... do something here with $segments? ....
    }
}

Upvotes: 2

Mike Brant
Mike Brant

Reputation: 71422

You have a few layers of arrays nested in there. I think your code needs to change to this:

$trips = $routings[0]->trips;
$segments = $trips[0]->segments;

Upvotes: 0

Related Questions