JSON output for items - php

I am having a code like below . I am reading a JSON URL and echo some items with some if conditions. I am in need to re echo the selected items in JSON format.
<?php
// Array of trains to list
//Arrival train list
$trainNumbers = array(
9021,11077
);
$json = file_get_contents('myURL.json');
$trainData = json_decode($json, true);
foreach ($trainData[0] as $train) {
$trainNumber = $train[0][0];
if (in_array($trainNumber, $trainNumbers)) {
$fields = array(
'train_no',
'train_name',
'dep_date',
'dep_station',
'dep_log',
'dep_lat',
'arr_station',
'delay_time',
'new_lat',
'new_long',
'new_station',
'new_station_name',
'time_delay',
'station_left'
);
foreach ($train[0] as $i => $dataField) {
echo $fields[$i] . " - {$dataField}\n";
$trains[$trainNumber][$fields[$i]] = $datafield;
}
echo "\n";
}
}
?>
The above code display data like
train_no - 09021
train_name - MUMBAI BANDRA T - JAMMU TAWI Exp (SPL)
dep_date - 2013-05-06
dep_station - BRSQ
dep_log - 28.613196
dep_lat - 77.14046
arr_station - BRAR SQUARE
delay_time - 150
new_lat - 28.659977
new_long - 77.156425
new_station - UMB
new_station_name - AMBALA CANT JN
time_delay - 48
station_left - 67
train_no - 11077
train_name - PUNE - JAMMU TAWI Jhelum Express
dep_date - 2013-05-06
dep_station - HET
dep_log - 26.611628
dep_lat - 77.943449
arr_station - HETAMPUR
delay_time - 56
new_lat - 26.697312
new_long - 77.905769
new_station - DHO
new_station_name - DHAULPUR
time_delay - 44
station_left - 93
How can I echo the output again in JSON format ?
on edit as suggested below
$data[$fields[$i]]= " - {$dataField}\n";
echo json_encode($data);
I am getting this error
Here is teh JSON output
http://pastebin.com/7EeVg8X9
Actually in this script we have list for 100's trains so I called some of the trains from that.

Currently, your problem is that you are outputting each mapped 'train' as a separate item. In order for the output to represent valid JSON, at a minimum the separate elements should be collected into an array. Here is a slightly modified version of your program:
<?php
// Fields to be translated
$fields = array(
'train_no',
'train_name',
'dep_date',
'dep_station',
'dep_log',
'dep_lat',
'arr_station',
'delay_time',
'new_lat',
'new_long',
'new_station',
'new_station_name',
'time_delay',
'station_left'
);
// Array of trains to list
//Arrival train list
$trainNumbers = array(
9021,11077
);
$json = file_get_contents('myurl.json');
$trainData = json_decode($json, true);
foreach ($trainData[0] as $train) {
$trainNumber = $train[0][0];
if (in_array($trainNumber, $trainNumbers)) {
foreach ($train[0] as $i => $dataField) {
$data[$fields[$i]]= $dataField;
}
$translated[] = $data;
}
}
echo json_encode($translated);
?>
Which outputs (after formatting with jsonlint):
[
{
"train_no": "09021",
"train_name": "MUMBAI BANDRA T - JAMMU TAWI Exp (SPL)",
"dep_date": "2013-05-06",
"dep_station": "HUK",
"dep_log": "28.801247",
"dep_lat": "77.102394",
"arr_station": "HOLAMBI KALAN",
"delay_time": "172",
"new_lat": "28.846516",
"new_long": "77.085357",
"new_station": "UMB",
"new_station_name": "AMBALA CANT JN",
"time_delay": 70,
"station_left": 64
},
{
"train_no": "11077",
"train_name": "PUNE - JAMMU TAWI Jhelum Express",
"dep_date": "2013-05-06",
"dep_station": "BHA",
"dep_log": "27.06879445",
"dep_lat": "77.96653748",
"arr_station": "BHANDAI",
"delay_time": "59",
"new_lat": "27.157722",
"new_long": "77.989883",
"new_station": "AGC",
"new_station_name": "AGRA CANTT",
"time_delay": 45,
"station_left": 92
}
]
You could choose to use a different kind of JSON output (for example a root object with each train keyed by name, or whatever else). Just extend the same principle as shown above in order to generate valid JSON.

Use json_encode for encodeing data into json
$data[$fields[$i]]= $dataField;
echo json_encode($data);
You will get more help from Here

Related

Overpass API and json output in PHP

I am using Overpass Turbo to show information on a map.
Part of my code (I use PHP) is as follows:
//overpass query
$overpass = 'http://overpass-api.de/api/interpreter?data=[out:json];area(3600046663)->.searchArea;(node["amenity"="drinking_water"](area.searchArea););out;';
// collecting results in JSON format
$html = file_get_contents($overpass);
$jsonout = json_decode($html);
// this line just checks what the query would give as output
var_dump($jsonout);
Query results in JSON format (which is what var_dump shows) look like this:
version: 0.6
generator: "Overpass API"
osm3s:
timestamp_osm_base: "2017-11-03T06:25:02Z"
timestamp_areas_base: "2017-11-03T05:45:02Z"
copyright: "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
elements:
0:
type: "node"
id: 254917402
lat: 46.0672187
lon: 11.1379545
tags:
amenity: "drinking_water"
1:
type: "node"
id: 257481472
lat: 46.0687113
lon: 11.1201097
tags:
amenity: "drinking_water"
and so on.
You can see it yourself, copying/pasting the query URL in your browser: http://overpass-api.de/api/interpreter?data=[out:json];area(3600046663)-%3E.searchArea;(node[%22amenity%22=%22drinking_water%22](area.searchArea););out;
As you can see, each element in the array above has latitude and longitude information. I need those to show markers on a map.
I am not able to isolate the lat and lon information from each element in the array. How can I do that?
Here you go:
<?php
// overpass query
$overpass = 'http://overpass-api.de/api/interpreter?data=[out:json];area(3600046663)->.searchArea;(node["amenity"="drinking_water"](area.searchArea););out;';
// collecting results in JSON format
$html = file_get_contents($overpass);
$result = json_decode($html, true); // "true" to get PHP array instead of an object
// elements key contains the array of all required elements
$data = $result['elements'];
foreach($data as $key => $row) {
// latitude
$lat = $row['lat'];
// longitude
$lng = $row['lon'];
}
?>

How to lookup data in a json file using php

Using PHP, I'm looking to get an id passed via the url and then lookup some data in a JSON file... then display the data back on the page.
I'll set up the url to be http://mytestapp.php?id=12345678 and then use;
$id = $_GET['id'];
to set the id variable. I then have a JSON as below;
{
"ads":
[
{ "id":"12345678",
"hirername":"Test Hirer",
"hirercontact":"Rob A",
"role":"Ultra Sat Role",
"requirements": [
{"req":"Right to work in Australia"},
{"req":"Live locally"}],
"candidates": [
{"name":"John Smith","dist":"Nunawading (23km away)","exp1":"Pizza maker at Don Domenicos for 4 years","exp2":"Bakery Assistant at Woolworths for 4 years","req":"","avail1":"Mon to Fri | Morning, Evening & Night","avail2":"","call":"0413451007"},
{"name":"Jack Smith","dist":"Endeadvour Hills (35km away)","exp1":"Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year","exp2":"","req":"","avail1":"Mon to Fri | Morning & Evening","avail2":"","call":"041345690"}]
},
{ "id":"12345679",
"hirername":"Test Hirer 2",
"hirercontact":"Jesse S",
"role":"Ultra Sat Role 2",
"requirements": [
{"req":"Right to work in Australia"},
{"req":"Live locally"}],
"candidates": [
{"name":"Jill Smith","dist":"Nunawading (23km away)","exp1":"Pizza maker at Don Domenicos for 4 years","exp2":"Bakery Assistant at Woolworths for 4 years","req":"","avail1":"Mon to Fri | Morning, Evening & Night","avail2":"","call":"0413451007"},
{"name":"Jenny Smith","dist":"Endeadvour Hills (35km away)","exp1":"Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year","exp2":"","req":"","avail1":"Mon to Fri | Morning & Evening","avail2":"","call":"041345690"}]
}
]
}
Which i want to search for the id, and then be able to echo the contents of the data out.
I'm reading the JSON and decoding into an array as such;
$json = file_get_contents('data.json');
$arr = json_decode($json, true);
But i'm not sure how to now read the array, find the data i want based on the id, and then pull out the data so i can display it on the page as follows;
Hirer: Test Hirer
Contact: Rob A
Role: Ultra Sat Role
Requirements:
- Right to work in Australia
- Live Locally
John Smith Nunawading (23km away)
Pizza maker at Don Domenicos for 4 years
Bakery Assistant at Woolworths for 4 years
Mon to Fri | Morning, Evening & Night
0413451007
Jack Smith Endeadvour Hills (35km away)
Pizzaiolo (Pizza maker) at Cuor Di Pizza for 1 year
Mon to Fri | Morning & Evening
041345690
Any ideas?
Thanks Rob.
Borrowed the example from #RobbieAverill and modified to suit your needs, please check if this works.
<?php
$id = $_GET['id'];
$json = file_get_contents('data.json');
$foundAd = null;
$json = json_decode($json,true);
foreach ($json['ads'] as $ad) {
if ($ad['id'] == $id) {
$foundAd = $ad;
break;
}
}
echo "Hirer:".$foundAd['hirername']."<br/>";
echo "contact:".$foundAd['hirercontact']."<br/>";
echo "role:".$foundAd['role']."<br/><br/>";
echo "Requirements<br/>";
echo "<ul>";
foreach($foundAd['requirements'] as $req){
echo "<li>".$req['req']."</li>";
}
echo "</ul><br/>";
foreach($foundAd['candidates'] as $req){
echo $req['name']." ". $req['dist']."</br>";
echo $req['exp1']."</br>";
echo $req['exp1']."</br>";
echo $req['avail1']."</br>";
if($req['avail2']!=""){
echo $req['avail2']."</br>";;
}
echo $req['call']."</br></br>";
}
?>
In your current inplementation you need to loop over all the ads objects like
foreach ($arr['ads'] as $ad){
if ($ad['id'] == $id){
//do stuff;
}
}
A better implementation would be to use the value of the id as the key of the json object when you store the json. Using something like
$ads[id] = $yourjsonobject;
Then referencing would just be $arr['ads'][id];.
You can then use multiple foreach or if your keys are knows just use the keys to output the object you need like
echo $ad["hirername"];
Using the foreach loop to print the complete object:
foreach( $ad as $value){
print_r($value);
}

Create and sort array to arrange events by time

The data I have to work with looks like this:
<div><strong><?php echo $form_data['field'][86]);?></strong> - Guests find seats</div>
<div><strong><?php echo $form_data['field'][87];?></strong> - Bridal party introductions</div>
<div><strong><?php echo $form_data['field'][88];?></strong> - Dinner is served</div>
<div><strong><?php echo $form_data['field'][92];?></strong> - Cake cutting</div>
<div><strong><?php echo $form_data['field'][96];?></strong> - Speeches</div>
<div><strong><?php echo $form_data['field'][188];?></strong> - Blessing</div>
<div><strong><?php echo $form_data['field'][107];?></strong> - First Dances</div>
But that example data is rarely consistent. For example, there may not be a cake cutting, also the order as shown is not correct.
However, the $form_data values are ALWAYS 24 hour fomats (ie. 14:00, 03:30, etc.)
I want to be able to take all the existing strings (whichever one's are not blank) and create an array that includes the time and event type and then echoes the output in the correct order.)
So the array would always include those 7 string values, but there may be times that only 5 or 6 of them are relevant.
Thank you for any help you can provide.
How about this for an idea. I think I follow your question, but dont beat me up if I missed something.
Write a little PHP to create a seperate array from the relevant items from $form_data array, add the labels to that array as well so you know what you are putting out onto the page
<?php
$pickupList = array(86 => 'Guests find seats',
87 => 'Bridal party introductions',
88 => 'Dinner is served',
92 => 'Cake cutting',
96 => 'Speeches',
188 => 'Blessing',
107 => 'First Dances'
);
$event_order = array();
foreach ( $pickupList as $key=> $label ) {
if ( $form_data['field'][$key] != '' ) {
$event_order[$form_data['field'][$key]] = $label;
}
}
ksort($event_order); // sort on key which is a time 12:15
foreach ( $event_order as $time => $event) {
echo '<div><strong>';
echo $time;
echo '</strong> - ';
echo $event;
echo '</div>';
}

How do you rearrange text within a string from a MySQL query?

Solution I am looking for:
I would like to rearrange words within the text string results such that the job title is moved from the end of the string to the beginning of the string for each line item.
Currently, I am retrieving data from an external medical database query ($query). However, I cannot make any changes to the database or to the MySQL query statement itself.
The $query is retrieved and I then place the results in a $data array via the following command:
while($row = mysql_fetch_assoc($query)){$data[] = $row;}
I then change all the job titles to uppercase in the $data array as follows:
$job_01 = 'anesthesiologist';
$job_02 = 'dentist';
$job_03 = 'general practitioner';
$job_04 = 'internist';
$job_05 = 'lawyer';
$job_06 = 'manager';
$job_07 = 'pediatrician';
$job_08 = 'psychiatrist';
$replace_01 = 'ANESTHESIOLOGIST';
$replace_02 = 'DENTIST';
$replace_03 = 'GENERAL PRACTITIONER';
$replace_04 = 'INTERNIST';
$replace_05 = 'LAWYER';
$replace_06 = 'MANAGER';
$replace_07 = 'PEDIATRICIAN';
$replace_08 = 'PSYCHIATRIST';
$searchArray = array($job_01, $job_02, $job_03, $job_04, $job_05, $job_06, $job_07, $job_08);
$replaceArray = array($replace_01, $replace_02, $replace_03, $replace_04, $replace_05, $replace_06, $replace_07, $replace_08);
for ($i=0; $i<=count($data)-1; $i++) {
$line[$i] = str_ireplace($searchArray, $replaceArray, $data[$i]));
}
The final output is in the following line item text string format:
Example Query results (4 line items)
California Long time medical practitioner - ANESTHESIOLOGIST 55yr
New York Specializing in working with semi-passive children - PEDIATRICIAN (doctor) 42yr
Nevada Currently working in a new medical office - PSYCHIATRIST 38yr
Texas Represents the medical-liability industry - LAWYER (attorney) 45yr
I would like to rearrange these results such that I can output the data to my users in the following format by moving the job title to the beginning of each line item as in:
Desired results (usually over 1000 items)
ANESTHESIOLOGIST - California Long time medical practitioner - 55yr
PEDIATRICIAN - New York Specializing in working with semi-passive children - (doctor) 42yr
PSYCHIATRIST - Nevada Currently working in a new medical office - psychiatrist 38yr
LAWYER - Texas Represents the medical-liability industry - lawyer (attorney) 45yr
Ideally, if possible, it would also be nice to have the age moved to the beginning of the text string results as follows:
Ideal Results
55yr - ANESTHESIOLOGIST - California Long time medical practitioner
42yr - PEDIATRICIAN - New York Specializing in working with semi-passive children - (doctor)
38yr - PSYCHIATRIST - Nevada Currently working in a new medical office - psychiatrist
45yr - LAWYER - Texas Represents the medical-liability industry - lawyer (attorney)
You could use a regular expression to extract and rearrange the array:
for ($i=0; $i<=count($data)-1; $i++) {
$line[$i] = str_ireplace($searchArray, $replaceArray, $data[$i]));
// variant a, complete line
if(preg_match_all('/(.*)\s+-\s+(.*)\s+(\d+)yr$/', $line[$i],$matches)) {
$line[$i] = $matches[3][0].'yr - '.$matches[2][0].' - '.$matches[1][0];
// variant b, a line with age, but no jobtitle
} elseif(preg_match_all('/(.*)\s+-\s+(\d+)yr$/', $line[$i],$matches)) {
$line[$i] = $matches[2][0].'yr - '.$matches[1][0];
// variant c, no age
} elseif(preg_match_all('/(.*)\s+-\s+(.*)$/', $line[$i],$matches)) {
$line[$i] = $matches[2][0].' - '.$matches[1][0];
}
// in other cases (no age, no jobtitle), the line is not modified at all.
}

How to output parts of a string array from text file from session in PHP

My page lets the user choose a list of courses that they wish to attend from a list opened up by the .php script. The choices the user picks are set to an array of check boxes called courses[]. One the Result.php, the choices chosen are sent through a RegEx to extract the course names and the hours that each course requires. The course name is only outputted while the hours are added up to show the total hours needed each week.
My problem is, I have fixed all syntax, but nothing is returned when I call out my printf format. I tried to var_dump($courses) and ($courseLine) and it came out to NULL and NULL. I think I have a piece of logic error on Registration.php but I cant find where.
Below is my Result.php and I will include a sample of the course list text file
<table><tr><th>Courses</th><th>hours per Week</th></tr>
<?php
$courses = $_GET['courses'];
$courseHoursRegEx = "/\s[0-9]{1,2}\shrs/w/";//needs work
$courseNameRegEx = "/[a-zA-Z]{3}[0-9]{4}[A-Z]{0,1}\s?/[a-zA-Z]{3,40}/";
function GetCourseHours($couseLine)
{
if(!preg_match($courseHoursRegEx, $courseLine))
{
return $courseHour;
}
$totalHours += $courseHour;
}
function GetCourseName($courseLine)
{
if(!preg_match($courseNameRegEx, $courseLine))
{
return $courseInfo;
}
}
foreach($courses as $course)
{
$theCourse = GetCourseName($course);
$theHours = GetCourseHours($course);
}
for($i = 1; $i <= $courses; ++$i)
{
printf("<tr><td>\%</td><td>\%</td></tr>", $theCourse, $theHours);
}
?>
<tr>
<th>Total Hours</th><td><?php echo $totalHours ?> </td></tr>
</table>
Here is my starting page, so you have an idea what values are worked with (I did not include the validation functions due the the length of script.)
</table>
<?php
$courseFile = fopen("CourseList.txt", "r");
$courseHoursRegEx = "/\s[0-9]{1,2}\shrs/w/";
$courseNameRegEx = "/[a-zA-Z]{3}[0-9]{4}[A-Z]{0,1}\s?/[a-zA-Z]{3,40}/";
while(!feof($courseFile))
{
$courseLine = fgets($courseFile);
echo "<input type='checkbox' name='courses[]' value='$courseLine'/> $courseLine <br />";
}
fclose($courseFile);
function GetCourseHours($courseLine)
{
if(!preg_match($courseHoursRegEx, $courseLine))
{
return $courseLine;
}
}
function GetCourseName($courseLine)
{
if(!preg_match($courseNameRegEx, $courseLine))
{
return $courseLine;
}
}
?>
Here is a sample of what the text file looks like with course information
CON8101 Residential Building/Estimating 16 hrs/w
CON8411 Construction Materials I 4 hrs/w
CON8430 Computers and You 4 hrs/w
MAT8050 Geometry and Trigonometry 4 hrs/w
SAF8408 Health and Safety 5 hrs/w
while not specifically answering your question, try using the following regex on each line in your file;
preg_match('/(?P<courseid>[A-Z0-9]+) (?P<coursename>.*) (?P<coursehours>\d+) hrs/',$text,$matches);
this will create an array $matches in this case which you can then reference the elements more inately
Array
(
[0] => CON8101 Residential Building/Estimating 16 hrs
[courseid] => CON8101
[1] => CON8101
[coursename] => Residential Building/Estimating
[2] => Residential Building/Estimating
[coursehours] => 16
[3] => 16
)
which will simplify your code and addition functions immensely.
=+ is not a valid php operator try += If your using numbers try += if strings use .=. Hope that works.

Categories