How to lookup data in a json file using php - 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);
}

Related

JSON url field is not correctly displaying

So this is where to view my json file: http://alyssayango.x10.mx/
this is my php file for that:
<?php
include('connectdb.php');
$sql = "SELECT * FROM tblmovies ORDER BY _id";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$set = array();
while($row1 = mysql_fetch_assoc($result)) {
$set[] = $row1;
}
echo json_encode($set);
and the output is:
[{"_id":"3","movie_name":"Despicable Me 2","movie_cinema_number":"CINEMA 1","movie_length":"1hr. 40mins.","movie_type":"GP","movie_schedules":"12:10 PM | 02:25 PM | 04:40 PM","movie_image_url":"http:\/\/i39.tinypic.com\/szizo4.jpg"},{"_id":"4","movie_name":"White House Down","movie_cinema_number":"CINEMA 2","movie_length":"2 hrs. 10 mins.","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:20 PM | 06:10 PM","movie_image_url":"http:\/\/i39.tinypic.com\/vp9n9j.jpg"},{"_id":"5","movie_name":"My Lady Boss","movie_cinema_number":"CINEMA 3","movie_length":"1hr. 50 mins.","movie_type":"PG-13","movie_schedules":"01:00 PM | 03:30 PM | 06:00 PM","movie_image_url":"http:\/\/i44.tinypic.com\/2qlv08z.jpg"},{"_id":"6","movie_name":"Four Sisters And A Wedding","movie_cinema_number":"CINEMA 4","movie_length":"2 hrs. 5 mins. ","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:10 PM | 05:50 PM","movie_image_url":"http:\/\/i44.tinypic.com\/9iv0d1.jpg"}]
what seems to be wrong that I do in here? URL is displayed as: http:\ /\ /i44.tinypic.com\ /9iv0d1.jpg where it should be http://i44.tinypic.com/9iv0d1.jpg
The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
If you create an API that should be:
$array = array("title" => "TEST", "username" => "test"); // Creating a array
echo json_encode($array); // Printing json
Client want to request and get response:
$json = file_get_contents('http://www.example.com/test/films.json'); // Your url
$array = json_decode($json); // Your first array its here!
More: http://en.wikipedia.org/wiki/JSON
Warning: You can't edit or tidy your json response! It is good!
The problem does not exists, actually.
What you're doing wrong is that you're using a piece of your JSON string without decoding it beforehand. Just use json_decode(..) if you're within PHP or the equivalent javascript function to decode JSON.
Once you did that, you'll have an object / an array which contains the data in the correct form.

JSON output for items

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

Json Decode,Access, show and separate names with ID, every 9 names

Hello :) I give you the Json Decode below.
http://pastebin.com/XqhTMWCS
It presents my last 10 games. I need to get my 4 teamates for every game,and my 5 enemies.(names) When someone is a teamate, his "teamId" is 100 and when someone is an enemy,the "teamId" is 200. I need to separate and show them.
Like: You were playing Vayne. Your team was:
sirjack1101 playing champion ID 89
blablaa playing ID 22
blablaaa playing ID 23
blablaaaa playing ID 24
The enemy team was:
blablsaa playing ID 31
bsadaaas playing ID 12
basdasdb playing ID 53
blablsad playing ID 67
blablsav playing ID 121
I can find only the first username using this :
$recent = "My json" ;
$rec = file_get_contents($recent);
$recdat = json_decode($rec, true);
$fellow = $recdat[gameStatistics][0][fellowPlayers][0][summonerName];
echo $fellow;
And I can get only my 1st champion name using the same code... I need your help! :)
Thanks in advance!
Sounds like you just need a foreach loop to iterate over all players.
<?php
define('TEAMMATE_ID', 100);
define('ENEMY_ID', 200);
$teammates = $enemies = array();
foreach ($data['gameStatistics'][0]['fellowPlayers'] as $player) {
if ($player['teamId'] == TEAMMATE_ID) {
$teammates[] = $player['summonerName'] .' playing ID '. $player['championId'];
}
else if ($player['teamId'] == ENEMY_ID) {
$enemies[] = $player['summonerName'] .' playing ID '. $player['championId'];
}
}
// List of teammates.
print "Teammates:\n";
print implode("\n", array_slice($teammates, 0, 4));
// List of enemies.
print "Enemies:\n";
print implode("\n", array_slice($enemies, 0, 5));
?>
Hopefully I'm not way off base...

Json Decode Presentation With Category

I got these Json data:
[{"category":"Pizza","name":"Beef Pronto","desc":"Description of Beef Pronton here","price":"12"},
{"category":"Drink","name":"Cool Delight","desc":"Description of Coold Delight here","price":"5"},
{"category":"Drink","name":"Cola","desc":"Description of Cola","price":"4"}
]
With Javascript I have successfully managed data to present as follow:
Pizza
-Beef Pronto: Description of Beef Pronton here: 12
Drink
-Cool Delight: Description of Coold Delight here: 5
-Cola: Description of Cola: 4
any Idea how to do it with PHP ?
-->Ok guys, this is How I do it with PHP:
<?
$listedmenuJSON = '[{"category":"Pizza","name":"Beef Pronto","desc":"Description of Beef Pronton here","price":"12"},
{"category":"Drink","name":"Cool Delight","desc":"Description of Coold Delight here","price":"5"},
{"category":"Drink","name":"Cola","desc":"Description of Cola","price":"4"}
]';
$json_decoded = json_decode($listedmenuJSON);
foreach ($json_decoded as $categoryvalue){
//echo $categoryvalue->category."<br/>";
$tempcategoryvalue[] = $categoryvalue->category;
$arrunique = array_unique($tempcategoryvalue);
}
foreach ($arrunique as $tmpcategory){
echo '<br/><b>'.$tmpcategory.'</b></br>';
foreach ($json_decoded as $tempo){
if($tempo->category == $tmpcategory){
echo $tempo->name.'<br/>';
echo '<i>'.$tempo->desc.'.......</i>';
echo $tempo->price.'<br/>';
}
}
}
?>
It will generate as following:
Pizza
Beef Pronto
Description of Beef Pronton here.......12
Drink
Cool Delight
Description of Coold Delight here.......5
Cola
Description of Cola.......4
If you got json in PHP Code Use Following line to convert json to PHP array and manipulate array for desire output
$array = json_decode($json,TRUE);
In javascript user below code to convert your json to array.
var obj = jQuery.parseJSON(responce);
Try using the PHP function 'json_decode' (http://php.net/manual/en/function.json-decode.php). This will create an associative array in PHP. It should be pretty simple to access and manipulate data thereon.
If you use a SQL server then you can select form the table using "group by category"
Else, you can just verify many times the arrays.
SQL:
<?php
$query = "SELECT * FROM 'table'
GROUP BY category
having (category=\"Pizza\");"
--SELECT * FROM 'table'
--GROUP BY category
--having (category="Drink");
if you use this in php you must use sql_query("query")

How can I put rows of MySQL data under the appropriate titles using PHP?

I have the following MySQL table structure:
num field company phone website
1 Gas abcd 123456789 abcd.com
2 Water efgh 987654321 efgh.com
3 Water ijkl 321654987 ijkl.com
4 Heat mnop 987654321 mnop.com
5 Gas qrst 123789654 qrst.com
...
Is it possible with PHP (maybe using some mixture of GROUP_BY and ORDER_BY) to echo the data to the screen in the following format:
Gas:
abcd qrst
123456789 123789654
abcd.com qrst.com
Water:
efgh ijkl
987654321 321654987
efgh.com ijkl.com
Heat:
mnop
321654987
mnop.com
The exact format of it isn't important. I just need for the different rows of data to be listed under the appropriate field with none of the fields repeated. I've been trying to figure this out for a while now, but I'm new to PHP and I can't seem to figure out how to do this, if it's even possible, or if there's a better way to organize my data to make it easier.
To avoid performing a "Gas" query, a "Water" query and a "Heat" query, you could order the results by "field" and then handle the display in PHP...
SELECT
Field,
Company,
Phone,
Website
FROM
tblYourTable
ORDER BY
Field
In your PHP loop, you would need to keep tabs on your current "Field" and start a new list when it changes. For example:
$CurrentField = '';
... loop
if ($MyData->Field != $CurrentField) {
$CurrentField = $MyData->Field;
....
}
... end loop
I will assume that you know how to retrieve MySQL data into an array... so, we have:
[0] {
num => 1,
field => "Gas",
company => "abcd",
phone => "123456789",
website => "abcd.com"
}
[1] ... (so on)
Then create a loop like:
foreach($data as $row) {
$service = $row["field"]; //Water, Gas, etc...
unset($row["field"]); //do not add this
foreach($row as $key => $value) {
$field[$service][$key][] = $value;
}
}
The resulting array will be something like:
$field["Gas"]["company"][0] = "abcd";
$field["Gas"]["company"][1] = "qrst";
$field["Water"]["company"][0] = "efgh";
...
$field["Gas"]["phone"][0] = "123456789";
$field["Gas"]["phone"][1] = "123789654";
$field["Water"]["phone"][0] = "987654321";
...
In that way you can then generate the output:
foreach($field as $service => $infoarr) {
echo $service."\n";
foreach($infoarr as $info => $datarr) {
foreach($datarr as $datum) {
echo $datum."\t";
}
echo "\n";
}
echo "\n";
}
Theorically (untested) will output:
Gas
abcd qrst
123456789 123789654
Water
efgh ...
I hope you find it useful... There should be a better way, but I didn't thought
too much about it...

Categories