echo parts of json returned in php - php

my returned json looks like this http://pastebin.com/Nbr161s3
I want to echo
body->airTicketListResponse->routings->mainAirlineName
body->airTicketListResponse->routings->adultBasePrice
body->airTicketListResponse->routings->trips->segments->departureAirportCode
body->airTicketListResponse->routings->trips->segments->departureTime //only the time here
body->airTicketListResponse->routings->trips->segments->duration
for each routings.
How do I do this? Here is what I have but I am lost and I know it is way off.
$result = data returned here http://pastebin.com/Nbr161s3
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $result->body->airTicketListResponse->routings;
$trips = $result->body->airTicketListResponse->routings->trips;
$segments = $result->body->airTicketListResponse->routings->trips->segments;
foreach($airTicketListResponse as $item){
$i=0;
$i<count($routings);
echo '<span style="font-weight:bold;">Airline - '.$item->routings[i]->mainAirlineName.' Price - '.$item->routings[i]->adultBasePrice.'</span><br />'.$item->routings[i]->trips[i]->segments[i]->departureAirportCode.' '.$item->routings[i]->trips[i]->segments[i]->departureTime.'<br /><br />';
$i++;
}
Please help if you can.

Before working with JSON you should be familiar with working with arrays and objects since JSON is nothing more than that.
It seems you already know these two concepts
To access an object property in PHP you use obj->property
To access a value of an array you specify the index inside brackets array[0]
With JSON you just have to keep in mind that some of your object properties will be arrays.
Now, since your data comes in a multi-level three-like structure you should also be familiar with traversing arrays, PHP offers an implementation of a foreach loop that is ideal for traversing dynamically generated arrays
using foreach($array as $index => $var) the $index and $var variables are automatically set to the index and value of each element in the array as they are being traversed, so you don't manually need to keep track of the index (i.e. $i)
Now let's start going through your data:
First we find your routings array
$result = json_decode($data);
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $airTicketListResponse->routings;
Now we use foreach to loop through every routing and print the needed properties
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
}
Getting single properties like the above is pretty straight forward, but for the information of the segments we would first need a nested foreach since we have multiple trips for each routing and then a second nested foreach since each trip has multiple segments
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
foreach($routing->trips as $trip){
foreach($trip->segments as $index => $segment){
echo 'Segment '.$index.':<br>'
echo 'Depart From '.$segment->departureAirportCode.'<br>';
echo 'Departure Time '.$segment->departureTime.'<br>';
echo 'Duration '.$segment->duration.'<br>';
}
}
}
And that would be it. I hope my explanation was clear and you got the idea of how to traverse JSON objects

If you feel more comfortable working with an array than with an object to access your data [which might be where you're getting confused here] then you can use json_decode with an additional argument:
$data = json_decode($result, true);
This will leave you with an array ($data) containing all your flight information, you can then var_dump() it and see the hierarchy you're dealing with and loop through it.

Related

PHP extract key-value in array json and restructure

Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.

How to get data from array [API/JSON]

I'm currently trying to get going with API's but i'm finding it really hard to extract the data from the api into my webpage.
I have tried using json_decode($, true), and it works OK, but some data I just cant extract.
Like, in this example, how would you get the name?
{"id":12345678,"name":"MyAwesomeLeagueName","profileIconId":593,"summonerLevel":30,"revisionDate":1389164617000}
I have used for getting data from others, but cant really get it to work with types like this one.
//put json in array
$r = json_decode($r, true);
echo $r['champions'][1]['attackRank'];
Also, if anyone have some good JSON -> PHP Tutorials I would really appreciate.
In that example to access the name you just need to refer to $r['name'] e.g.
echo $r['name'];
After decoding the JSON string, do a var_dump on your array and it will show you the contents and how to access.
To get all with a certain magic rank as per your example, you'd need to loop through the array and test the value of the particular key:
$r = json_decode($r, true);
//loop through $r
foreach ($r['champions'] as $key => $value) {
if ($value['magicRank'] != 8) {
//if magicRankis not 8, ignore and move on to the next entry
continue;
}
//magicRank is 8, do something
echo $value['name'] . " has magic rank of 8<br />";
}

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 />';
}
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? ....
}
}
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;

How to use JSON with unknown multiple keys (PHP)

I am receiving a JSON String, which has multiple unknown keys. It's pretty hard to explain, because those JSON strings are pretty large, I'll try to break them down in the most efficient way.
I use PHP to break down the object, that I get, when I decode the JSON string.
$data1 = $json->result->map->12313214654[0]
$data2 = $json->result->map->12313214654[2]
$differentdata1 = $json->result->map->12313214655[0]
As you can see, there are different subsections after the map key.
Those are numbers, that are pretty random. And their appearance isn't regular either. So sometimes there's just one subsection (or number), and sometimes more.
How can I access them? I tried to use $datacount = $count($json->result->map) But it always displays 1. And then I still wouldn't be able to access the subelements of the map key.
Does anyone have a solution for this?
As you seem to have an unknown amount of data in array form, you could iterate your results with a foreach loop:
foreach ($json->result->map as $key => $dataArray) {
// $key will be the numeric key, e.g. 12313214654
// $dataArray will be the array of data you're after
foreach ($value as $dataIndex => $data) {
// $dataIndex is the position of $data within the $dataArray
// $data is the value you were trying to access with $json->result->map->12313214654[n]
// You do your work with $data here.
print_r($data);
}
}

Autofill array with empty data to match another array size

I have 2 sets of arrays:
$dates1 = array('9/12','9/13','9/14','9/15','9/16','9/17');
$data1 = array('5','3','7','7','22','18');
// for this dataset, the value on 9/12 is 5
$dates2 = array('9/14','9/15');
$data2 = array('12','1');
As you can see the 2nd dataset has fewer dates, so I need to "autofill" the reset of the array to match the largest dataset.
$dates2 = array('9/12','9/13','9/14','9/15','9/16','9/17');
$data2 = array('','','12','1','','');
There will be more than 2 datasets, so I would have to find the largest dataset, and run a function for each smaller dataset to properly format it.
The function I'd create is the problem for me. Not even sure where to start at this point. Also, I can format the date and data arrays differently (multidimensional arrays?) if for some reason that is better.
You can do this in a pretty straightforward manner using some array functions. Try something like this:
//make an empty array matching your maximum-sized data set
$empty = array_fill_keys($dates1,'');
//for each array you wish to pad, do this:
//make key/value array
$new = array_combine($dates2,$data2);
//merge, overwriting empty keys with data values
$new = array_merge($empty,$new);
//if you want just the data values again
$data2 = array_values($new);
print_r($data2);
It would be pretty easy to turn that into a function or put it into a for loop to operate on your array sets. Turning them into associative arrays of key/value pairs would make them easier to work with too I would think.
If datas are related will be painful to scatter them on several array.
The best solution would be model an object with obvious property names
and use it with related accessor.
From your question I haven't a lot of hint of what data are and then I have to guess a bit:
I pretend you need to keep a daily log on access on a website with downloads. Instead of using dates/data1/data2 array I would model a data structure similar to this:
$log = array(
array('date'=>'2011-09-12','accessCount'=>7,'downloadCount'=>3),
array('date'=>'2011-09-13','accessCount'=>9), /* better downloadsCount=>0 though */
array('date'=>'2011-09-15','accessCount'=>7,'downloadCount'=>3)
...
)
Using this data structure I would model a dayCollection class with methods add,remove,get,set, search with all methods returning a day instance (yes, the remove too) and according signature. The day Class would have the standard getter/setter for every property (you can resolve to magic methods).
Depending on the amount of data you have to manipulate you can opt to maintain into the collection just the object data (serialize on store/unserialize on retrieve) or the whole object.
It is difficult to show you some code as the question is lacking of details on your data model.
If you still want to pad your array than this code would be a good start:
$temp = array($dates, $data1, $data2);
$max = max(array_map('count',$temp));
$result = array_map( function($x) use($max) {
return array_pad($x,$max,0);
}, $temp);
in $result you have your padded arrays. if you want to substitute your arrays do a simple
list($dates, $data1, $data2) = array_map(....
You should use hashmaps instead of arrays to associate each date to a data.
Then, find the largest one, cycle through its keys with a foreach, and test the existence of the same key in the small one.
If it doesn't exist, create it with an empty value.
EDIT with code (for completeness, other answers seem definitely better):
$dates_data1 = array('9/12'=>'5', '9/13'=>'3', '9/14'=>'7' /* continued */);
$dates_data2 = array('9/14'=>'12', '9/15'=>'1');
#cycle through each key (date) of the longest array
foreach($dates_data1 as $key => $value){
#check if the key exists in the smallest and add '' value if it does not
if(!isset( $date_data2[$key] )){ $date_data2[$key]=''; }
}

Categories