Ok, I have been fighting this for two days now!! Here is my Json structure.
[
{
"uuid":"/random number==",
"meeting_number":7196503037,
"host_id":"random number",
"topic":"My's Personal Meeting Room",
"start_time":"2015-01-06T22:01:07Z",
"timezone":"America/Denver",
"duration":56,
"total_size":378080,
"recording_count":1,
"recording_files":[
{
"id":"long number",
"meeting_id":"/NS90bsSTLeGzo6cT0nwXw==",
"recording_start":"2015-01-06T22:01:09Z",
"recording_end":"2015-01-06T22:01:14Z",
"file_size":378080,
"play_url":"https://myurl"
}
]
},
I am trying to pull the Start Time from the top level array (which is named 'meetings') and the Play Url from the second level array (recording_files). I am using json_decode to decode the file into arrays.
I have tried many variations found on this site and nothing seems to get to the play url.
VARIATION 1
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
foreach($key['recording_files'] as $subkey => $newvalue){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}}
This pulls an invalid argument in foreach.
VARIATION 2
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This pulls undefined index for play_url. As does the same code with the reference to ['recording_files'] placed before ['play_url']
VARIATION 3:
Then I tried giving up on the first level and just pulling data from the second level:
$aha = json_decode($response,true);
foreach ($aha['meetings']['recording_files'] as $key => $value){
echo '<p>Time : '.$value['recording_start'].'</p>
Recording<br>';
}
That gives me an undefined index on ['recording_files'] and a foreach error.
VARIATION 4.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
$link=$key['recording_files'];
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';
}
This gets me the closest - no errors but no link. I presume that here the code is seeing the field but just not pulling the data from it...
Please help a newbie json person!!
If there is really an $aha['meetings'] (you don't show it), then use the value not the key in the second foreach:
foreach($aha['meetings'] as $value){
foreach($value['recording_files'] as $newvalue){
Final code that fixed it.
$aha = json_decode($response,true);
foreach ($aha['meetings'] as $key => $value){
echo '<p>Time : '.$value['start_time'].'</p>
Recording<br>';}
It was just a matter of finding the correct format for referencing the play_url piece.
Thank you so much to everyone!
Edit:
If your data looks like this :
$str = "{\"meetings\":[{
\"uuid\":\"/random number==\",
\"meeting_number\":7196503037,
\"host_id\":\"random number\",
\"topic\":\"My's Personal Meeting Room\",
\"start_time\":\"2015-01-06T22:01:07Z\",
\"timezone\":\"America/Denver\",
\"duration\":56,
\"total_size\":378080,
\"recording_count\":1,
\"recording_files\":[
{
\"id\":\"long number\",
\"meeting_id\":\"/NS90bsSTLeGzo6cT0nwXw==\",
\"recording_start\":\"2015-01-06T22:01:09Z\",
\"recording_end\":\"2015-01-06T22:01:14Z\",
\"file_size\":378080,
\"play_url\":\"https://myurl\"
}
]
}]}";
$json = json_decode($str);
$res = $json->{'meetings'};
foreach($res as $keys){
echo $keys->{'start_time'}."<br>";
foreach ($keys->{'recording_files'} as $data){
echo $data->{'play_url'}."<br>";
echo $data->{'recording_start'}."<br>";
}
}
Related
I'm using the Kraken API to get a list of available currency pairings.
Here is the endpoint: https://api.kraken.com/0/public/AssetPairs
$kraken_coins =
file_get_contents('https://api.kraken.com/0/public/AssetPairs');
$kraken_coins = json_decode($kraken_coins, true);
foreach ($kraken_coins['result'] as $coin) {
echo $coin . "<br>";
}
I'm trying to extract the first element inside of "result", however each of these elements are named differently so I'm not sure how to target it. For example, the first two currency pairings returned are "BCHEUR" and "BCHUSD".
So with the loop I have above, it just echos "Array" repeatedly... not what I'm going for.
How do I target that element so I can loop through each one? Thanks!
Since, the json structure is:
You need to use:
foreach ($array as $key => $value) {
}
In this case:
foreach ($kraken_coins['result'] as $coin => $coindata) {
echo $coin . "<br>";
}
I am using simplexml_load_string() in PHP to parse my XML File.
Now, for better reading, I json_encode()d my object:
http://pastebin.com/Hk8YCssR (Example Representation Plan of a german School)
I want one object with all actions in it and one with all keys of the "head".
I tried to loop through these keys, but I wasn't abled to get the value of a keys key, e.g.:
"action":[
{
"class":"5/2",
"period":"5",
...
In this case, to get the value "5/2".
I don't have the exact code, but I am writing in sketch what I've done:
$value = current((array)$xml);
echo $value;
foreach ($xml as $key) {
// echo $key[];
}
P.S.: Thank you for reading this
Try this:
$sv_infch=get_object_vars($xml[0]->info);
foreach($sv_infch as $key => $value) {
print "$key => $value\n";
echo "{$key} => {$value} ";
print_r($sv_infch);
}
I'm needing to know how to read through JSON in PHP that I don't know the key's for. Here is an example of a json that I would need to be going through however none of the key->value pair are always going to be the same. Some of these key names can be spelled different or have numbers on the end of the names so I need to be able to have them dynamic.
Here is an exact example of the JSON I would be cycling through
[
{
"var5":"item-company-1",
"asd2":"item-company-1",
"tie1":"0",
"cxs1":"481.891px",
"xcve2":"130.563px"
},...
I understand if I know the exact name of the key I would do something like..
$someObject = json_decode($someJSON);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->name; // Access Object data
However I don't know the keys. I assume a for next loop would have to be created to cycle through each object, but I have no clue how to do that in PHP.
Im assuming your json is always of the below format
$json = '[
{
"var5":"item-company-1",
"asd2":"item-company-1",
"tie1":"0",
"cxs1":"481.891px",
"xcve2":"130.563px"
},
{
"var6":"item-company-2",
"asd7":"item-company-2",
"tie8":"0",
"cxs9":"481.891px",
"xcve10":"130.563px",
"extra" : "unknown"
}
]';
Then you can convert the whole JSON into an array and run a loop
$array = json_decode ($json ,true);
foreach ($array as $item) {
foreach($item as $key => $value) {
echo $value;
}
}
I marked the answer because he technically answered my question.
I also found this solution hopefully it might help someone in the future as a great alternative to the above. This will actually go over a multi-level array to get out all the values.
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}
I'm trying to pull data from a CSV file that contains vehicle make, model, mileage etc...
Using this example from php -
<?php
$csv = array_map('str_getcsv', file('csv/csvin.csv'));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv);
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<div id='car'>".$key.":".$value."</div></br>";
}
}
?>
This is the array I get -
BodyStyle:"Station Wagon"
"DaysInStock":"27"
"Make":"Toyota"
"Model":"Prius v"
"MSRP":"0"
"SellingPrice":"26995"
"StockNumber":"387515"
"Trim":"Three"
"VIN":"JTDZN3EU9E3306528"
"Year" :"2014"
Now when I attempt to manipulate it or pull any individual values I simply cannot. How would I go about displaying this information with HTML tags for each value?
I have tried this:
print_r ($csv[0]['Make'];
echo $csv[0]['Make'];
Just to try and display a value but still nothing. I noticed for some reason the "BodyStyle" doesn't contain quotes like the rest so something definitely seems fishy.
From here how would I strip the quotes and break out each value?
This is the error being thrown -
Invalid argument supplied for foreach() in
Thanks in advance!
foreach($csv as $car){
echo "<tr><td>Make:</td><td>".$car['Make']."</td></tr>";
}
alternatively:
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<tr><td>".$key."</td><td>".$value."</td></tr>";
}
}
alternatively:
echo $csv[0]['Make'];
Try this one :
print_r ($csv[0]['Make']);
Basically the $csv variable is an array, to get its values you have to use the loop function, something like :
foreach ($csv as $data) {
foreach ($data as $index => $value) {
if ($index == "make") {
echo $value;
}
}
}
If you notice it a bit, the outer array is called indexed array (array with indexes) and to traverse the values use foreach ($csv as $data), while the inner array is called associative array (this array does not use number as index, but a name), and to traverse it use foreach ($data as $index => $value).
Try it and you'll see :)
PS: Sorry I didn't notice the inner array, for this case Richard's answer is the correct one. I have added a credit to his answer for giving a correct answer.
So I figured out that I only need 1 foreach loop like so -
foreach($csv as $car){
$type = $car[0];
$echo $type;
}
Works now and thanks all for the help!