I want to get value from my content such as #img::56:
#img::56 => value=56 to get record from datatabase mysql_query("select * from tblgallery where g_id=56");.
Tara Angkor Hotel is the first 4-Star Luxury Hotel built in the mystical land of Angkor. #img::56 Ideally and #youtube::https://www.youtube.com/watch?v=k4YRWT_Aldo conveniently located, Tara Angkor Hotel is situated only 6 km from the World Heritage site of Angkor Wat Temples, 15 min drive from the Siem Reap International Airport, a few minutes stroll to the Angkor National Museum and #img::41 a short ride to the city town center with an array of Cambodian souvenirs, shopping and culture.
I want to get result
Tara Angkor Hotel is the first 4-Star Luxury Hotel built in the mystical land of Angkor. mysql_query("select * from tblgallery where g_id=56") Ideally and <iframe width="560" height="315" src="//www.youtube.com/embed/k4YRWT_Aldo" frameborder="0" allowfullscreen></iframe> conveniently located, Tara Angkor Hotel is situated only 6 km from the World Heritage site of Angkor Wat Temples, 15 min drive from the Siem Reap International Airport, a few minutes stroll to the Angkor National Museum and mysql_query("select * from tblgallery where g_id=41") a short ride to the city town center with an array of Cambodian souvenirs, shopping and culture.
If I understand your question, you want to retrieve the 56 from the string #img::56?
If so it can be done as follows.
$string = '#img::56';
// Explode the string as the delimiter.
$components = explode('::', $string);
// Ensure the components array has two elements.
if(count($components) < 2) {
// Do something here to indicate an error has occurred.
//Throw an exception (preferred) or emit an error
}
$id = $components[1];
// You can use even more type checking here to ensure you have the right piece of data.
if(!ctype_digit($id)) {
//Throw an exception (preferred) or emit an error
}
// Accessing the database using a PDO object and prepared statements
$pdo = new \PDO('mysql:host=...', 'username', 'password')
$statement = $pdo->prepare('SELECT * FROM tblgallary WHERE g_id = :id');
$statement->bindParam(':id', $id, \PDO::PARAM_INT);
if(!$statement->execute()) {
//Throw an exception (preferred) or emit an error
}
$result = $statement->fetchAll(\PDO::FETCH_ASSOC);
// End the database connection
$pdo = null;
Now you have the id. If you need the $id to be an integer you can type cast it with (int) $components[1] instead.
Hope this helps.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Below is a php script for this algorithmic problem:
The SHIELD is a secretive organization entrusted with the task of
guarding the world against any disaster. Their arch nemesis is the
organization called HYDRA. Unfortunately some members from HYDRA had
infiltrated into the SHIELD camp. SHIELD needed to find out all these
infiltrators to ensure that it was not compromised.
Nick Fury, the executive director and the prime SHIELD member figured out that every one in SHIELD could send a SOS signal to every
other SHIELD member he knew well. The HYDRA members could send bogus
SOS messages to others to confuse others, but they could never receive
a SOS message from a SHIELD member. Every SHIELD member would receive
a SOS message ateast one other SHIELD member, who in turn would have
received from another SHIELD member and so on till NickFury. SHIELD
had a sophisticated mechanism to capture who sent a SOS signal to
whom. Given this information, Nick needed someone to write a program
that could look into this data and figure out all HYDRA members.
Sample Input
Nick Fury : Tony Stark, Maria Hill, Norman Osborn
Hulk : Tony Stark, HawkEye, Rogers
Rogers : Thor,
Tony Stark: Pepper Potts, Nick Fury
Agent 13 : Agent-X, Nick Fury, Hitler
Thor: HawkEye, BlackWidow
BlackWidow:Hawkeye
Maria Hill : Hulk, Rogers, Nick Fury
Agent-X : Agent 13, Rogers
Norman Osborn: Tony Stark, Thor
Sample Output
Agent 13, Agent-X, Hitler
SCRIPT.php
<?php
//this is the input
$input="Nick Fury : Tony Stark, Maria Hill, Norman Osborn
Hulk : Tony Stark, HawkEye, Rogers
Rogers : Thor
Tony Stark: Pepper Potts, Nick Fury
Agent 13 : Agent-X, Nick Fury, Hitler
Thor: HawkEye, BlackWidow
BlackWidow:HawkEye
Maria Hill : Hulk, Rogers, Nick Fury
Agent-X : Agent 13, Rogers
Norman Osborn: Tony Stark, Thor";
/*this is an array for storing shield member names as
key-value pairs like Nick Fury=>Tony Stark, Maria Hill, Norman Osborn*/
$shield=array();
$keys=array(); //array for storing shield member names as keys
$values=array(); //array for storing shield member names as value
$shield_members=array(); //array which stores each valid shield member's name using below process
//$hydra=array();
$rows = explode("\n", $input); //creating array of given input row wise
$i=0;
//considering each row at once
while ($i<count($rows)) {
# code...
$temp=explode(":", $rows[$i]); //exploding row
$key=trim($temp[0]); //getting key
$value=trim($temp[1]); //getting value
$keys[]=$key; //storing each key in keys[]
$values[]=$value; //storing each value in values[]
$shield[$key]=$value; //storing these key-value pair as array in shield[]
$i++;
}
//loop to find all persons who are receiving messages from anyone
$i=0;
$recieiver_hydra=array(); //arrray to store all persons receiving messages
while($i<count($values)){
$temp = explode(",", $values[$i]); //exploding RHS values row wise
$j=0;
while ($j<count($temp)) {
# code...
if(!in_array($temp[$j], $recieiver_hydra)) //trying insert only unique values in recieiver_hydra[]
$recieiver_hydra[]=$temp[$j]; //========BUT NOT GETTING=======
$j++;
}
$i++;
}
$shield_members[]= "Nick Fury"; //starting from Nick Fury
$temp = explode(",",$shield["Nick Fury"]); //getting value from shield[] array for given key
$i=0;
while($i<count($temp)){
$shield_members[]= $temp[$i]; //adding shield members which are valid not the hydra people
$i++;
}
/* searching process for each valid shield member starting from nick fury upto last one found
and storing them in the sheil_members[] array */
for($i=1; $i<30; $i++){ //=============HERE DON'T GETTING WHAT SHOULD BE THE CONDITION TO STOP EXECUTING
if (array_key_exists(trim($shield_members[$i]),$shield))
$temp = explode(",",$shield[trim($shield_members[$i])]);
else continue;
$j=0;
while ($j<count($temp)) {
# code...
$shield_members[] = trim($temp[$j]);
$j++;
}
}
$i=0;
//printing all valid members added to shield_members[] including duplicate values
while ( $i<count($shield_members)) {
# code...
echo $shield_members[$i]."<br>";
$i++;
}
asort($shield_members); //sorting them
$res1 = array_diff($keys, $shield_members); //finding difference and getting HYDRA members from LHS
$res2= array_diff($recieiver_hydra, $shield_members); //finding difference and getting HYDRA members from RHS ======BUT NOT GETTING
/*
<form action=<?php echo $_SERVER["PHP_SELF"]?> method="POST">
**<i> Enter input in the textarea... </i>
<textarea name="input" rows="10" cols="90"></textarea><br>
<input type="submit" name="submit" value="Find HYDRA Members">
</form>
*/
?>
As per my coding and expectations, $res1 must be having all HYDRA members from LHS of inputs and $res2 must be having all HYDRA members from RHS of input.
But when printing them I am getting wrong results.
$res1 = Array ( [4] => Agent 13 [8] => Agent-X ) //THIS IS CORRECT
$res2 = Array ( [3] => HawkEye [4] => Rogers [7] => Nick Fury
[8] => Agent-X [9] => Hitler [11] => BlackWidow
[13] => Agent 13 [14] => Thor ) //WRONG RESULTS
Please help me knowing what am I doing wrong?
(I am not expert at algorithms. Whole this code I made using raw coding ideas and knowledge.)
This sounds like a exercise from some programming course. Normally i would say, that you should solve such a task by yourself (I think this will be the reason for the down votes of your question), but it is a funny problem, so here is my solution.
If i need to implement a new algorithm, i always try to split the problem into subproblems.
Doing so,
it is easier to find a good solution
as result you get a much more readable code
So problem number one is to transform the input into an array structure to work with:
function transformInput($input) {
foreach (explode("\n", $input) as $row) {
list($receiver, $senders) = explode(':', $row);
$memberTree[trim($receiver)] = array_map('trim', explode(',', $senders));
}
return $memberTree;
}
The second problem is to find all real SHIELD members:
function extractShieldMembers($memberTree, $startMember, $shieldMembers = array()) {
$shieldMembers[] = $startMember;
if (array_key_exists($startMember, $memberTree)) {
foreach ($memberTree[$startMember] as $member) {
if (!in_array($member, $shieldMembers)) {
$shieldMembers = array_merge(
$shieldMembers,
extractShieldMembers($memberTree, $member, $shieldMembers)
);
}
}
}
return $shieldMembers;
}
With this two functions in your library, it is very easy to get the list with all SHIELD members:
$memberTree = transformInput($input);
$shieldMembers = array_unique(extractShieldMembers($memberTree, 'Nick Fury'));
Now, after knowing who really belongs to SHIELD you can find all HYDRA members with this functon:
function getHydraMembers($memberTree, $shieldMembers){
$allMembers = array();
foreach ($memberTree as $key => $value) {
$allMembers[] = $key;
$allMembers = array_merge($allMembers, $value);
}
return array_unique(array_diff($allMembers, $shieldMembers));
}
$hydraMembers = getHydraMembers($memberTree, $shieldMembers);
Is this the best solution for this problem?
I don't think so, because it was just a quick approach.
But as you can see, if you try to split your code into small logic functions, you get more readable code, that you can better debug.
You also don't need as many temporary variables and counter.
I need some sort of database or feed to access live scores(and possibly player stats) for the NFL. I want to be able to display the scores on my site for my pickem league and show the users if their pick is winning or not.
I'm not sure how to go about this. Can someone point me in the right direction?
Also, it needs to be free.
Disclaimer: I'm the author of the tools I'm about to promote.
Over the past year, I've written a couple Python libraries that will do what you want. The first is nflgame, which gathers game data (including play-by-play) from NFL.com's GameCenter JSON feed. This includes active games where data is updated roughly every 15 seconds. nflgame has a wiki with some tips on getting started.
I released nflgame last year, and used it throughout last season. I think it is reasonably stable.
Over this past summer, I've worked on its more mature brother, nfldb. nfldb provides access to the same kind of data nflgame does, except it keeps everything stored in a relational database. nfldb also has a wiki, although it isn't entirely complete yet.
For example, this will output all current games and their scores:
import nfldb
db = nfldb.connect()
phase, year, week = nfldb.current(db)
q = nfldb.Query(db).game(season_year=year, season_type=phase, week=week)
for g in q.as_games():
print '%s (%d) at %s (%d)' % (g.home_team, g.home_score,
g.away_team, g.away_score)
Since no games are being played, that outputs all games for next week with 0 scores. This is the output with week=1: (of the 2013 season)
CLE (10) at MIA (23)
DET (34) at MIN (24)
NYJ (18) at TB (17)
BUF (21) at NE (23)
SD (28) at HOU (31)
STL (27) at ARI (24)
SF (34) at GB (28)
DAL (36) at NYG (31)
WAS (27) at PHI (33)
DEN (49) at BAL (27)
CHI (24) at CIN (21)
IND (21) at OAK (17)
JAC (2) at KC (28)
PIT (9) at TEN (16)
NO (23) at ATL (17)
CAR (7) at SEA (12)
Both are licensed under the WTFPL and are free to use for any purpose.
N.B. I realized you tagged this as PHP, but perhaps this will point you in the right direction. In particular, you could use nfldb to maintain a PostgreSQL database and query it with your PHP program.
So I found something that gives me MOST of what I was looking for. It has live game stats, but doesn't include current down, yards to go, and field position.
Regular Season:
http://www.nfl.com/liveupdate/scorestrip/ss.xml
Post Season:
http://www.nfl.com/liveupdate/scorestrip/postseason/ss.xml
I'd still like to find a live player stat feed to use to add Fantasy Football to my website, but I don't think a free one exists.
I know this is old, but this is what I use for scores only... maybe it will help someone some day. Note: there are some elements that you will not use and are specific for my site... but this would be a very good start for someone.
<?php
require('includes/application_top.php');
$week = (int)$_GET['week'];
//load source code, depending on the current week, of the website into a variable as a string
$url = "http://www.nfl.com/liveupdate/scorestrip/ss.xml"; //LIVE GAMES
if ($xmlData = file_get_contents($url)) {
$xml = simplexml_load_string($xmlData);
$json = json_encode($xml);
$games = json_decode($json, true);
}
$teamCodes = array(
'JAC' => 'JAX',
);
//build scores array, to group teams and scores together in games
$scores = array();
foreach ($games['gms']['g'] as $gameArray) {
$game = $gameArray['#attributes'];
//ONLY PULL SCORES FROM COMPLETED GAMES - F=FINAL, FO=FINAL OVERTIME
if ($game['q'] == 'F' || $game['q'] == 'FO') {
$overtime = (($game['q'] == 'FO') ? 1 : 0);
$away_team = $game['v'];
$home_team = $game['h'];
foreach ($teamCodes as $espnCode => $nflpCode) {
if ($away_team == $espnCode) $away_team = $nflpCode;
if ($home_team == $espnCode) $home_team = $nflpCode;
}
$away_score = (int)$game['vs'];
$home_score = (int)$game['hs'];
$winner = ($away_score > $home_score) ? $away_team : $home_team;
$gameID = getGameIDByTeamID($week, $home_team);
if (is_numeric(strip_tags($home_score)) && is_numeric(strip_tags($away_score))) {
$scores[] = array(
'gameID' => $gameID,
'awayteam' => $away_team,
'visitorScore' => $away_score,
'hometeam' => $home_team,
'homeScore' => $home_score,
'overtime' => $overtime,
'winner' => $winner
);
}
}
}
//see how the scores array looks
//echo '<pre>' . print_r($scores, true) . '</pre>';
echo json_encode($scores);
//game results and winning teams can now be accessed from the scores array
//e.g. $scores[0]['awayteam'] contains the name of the away team (['awayteam'] part) from the first game on the page ([0] part)
I've spent the last year or so working on a simple CLI tool to easily create your own NFL databases. It currently supports PostgreSql and Mongo natively, and you can programmatically interact with the Engine if you'd like to extend it.
Want to create your own different database (eg MySql) using the Engine (or even use Postgres/Mongo but with your own schema)? Simply implement an interface and the Engine will do the work for you.
Running everything, including the database setup and updating with all the latest stats, can be done in a single command:
ffdb setup
I know this question is old, but I also realize that there's still a need out there for a functional and easy-to-use tool to do this. The entire reason I built this is to power my own football app in the near future, and hopefully this can help others.
Also, because the question is fairly old, a lot of the answers are not working at the current time, or reference projects that are no longer maintained.
Check out the github repo page for full details on how to download the program, the CLI commands, and other information:
FFDB Github Repository
$XML = "http://www.nfl.com/liveupdate/scorestrip/ss.xml";
$lineXML = file_get_contents($XML);
$subject = $lineXML;
//match and capture week then print
$week='/w="([0-9])/';
preg_match_all($week, $subject, $week);
echo "week ".$week[1][0]."<br/>";
$week2=$week[1][0];
echo $week2;
//capture team, scores in two dimensional array
$pattern = '/hnn="(.+)"\shs="([0-9]+)"\sv="[A-Z]+"\svnn="(.+)"\svs="([0-9]+)/';
preg_match_all($pattern, $subject, $matches);
//enumerate length of array (number games played)
$count= count($matches[0]);
//print array values
for ($x = 0; $x < $count ; $x++) {
echo"<br/>";
//print home team
echo $matches[1][$x]," ",
//print home score
$matches[2][$x]," ",
//print visitor team
$matches[3][$x]," ",
//print visitor score
$matches[4][$x];
echo "<br/>";
}
I was going through problems finding a new source for the 2021 season. Well I finally found one on ESPN.
http://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard
Returns the results in JSON format.
I recommend registering at http://developer.espn.com and get access to their JSON API. It just took me 5 minutes and they have documentation to make pretty much any call you need.
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.
}
This is my problem. I'm trying to retrieve a value from an XML url (from last.fm api). For example the biography of an artist.
I already know that I can do it simply like this (e.g. for Adele):
<?php
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
echo $info;
?>
This returns:
Adele Laurie Blue Adkins, (born 5 May 1988), is a Grammy Award-Winning English singer-songwriter from Enfield, North London. Her debut album, <a title="Adele - 19" href="http://www.last.fm/music/Adele/19" class="bbcode_album">19</a>, was released in January 2008 and entered the UK album chart at #1. The album has since received four-times Platinum certification in the UK and has sold 5,500,000 copies worldwide. The album included the hugely popular song <a title="Adele – Chasing Pavements" href="http://www.last.fm/music/Adele/_/Chasing+Pavements" class="bbcode_track">Chasing Pavements</a>. 19 earned Adele two Grammy Awards in February 2009 for Best New Artist and Best Female Pop Vocal Performance.
I would now like to put that result in a text file and store it on a folder on my website, for example: "http://mysite.com/artistdescriptions/adele.txt".
I've already tried:
<?php
$file_path = $_SERVER['DOCUMENT_ROOT'].'/artistdescriptions/adele.txt';
$xml = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=adele&api_key=b25b959554ed76058ac220b7b2e0a026");
$info = $xml->artist->bio->summary;
file_put_contents($file_path, serialize($info));
$file_contents = file_get_contents($file_path);
if(!empty($file_contents)) {
$data = unserialize($file_contents);
echo $data;
}
?>
But this unfortunately didn't work. Any help would be greatly appreciated!
Echo call magic method __toString(), but serialize doesn't, and in SimpleXMLElement isn't serialize allowed, so it throw an Exception. But you can call __toString() magic method by yourself, and this solve you problem.
Replace your line with mine
$info = $xml->artist->bio->summary->__toString();
I was wondering if anyone is aware of any PHP scripts which maps a UK City onto a Post Code.
I have found something like this:
case'North West England, England': {
$postcode = 'M1 2NQ';
break;
}
case'North East England, England': {
$postcode = 'NE1 6AD';
break;
}
case'South West England, England': {
$postcode = 'EX1 3AX';
break;
}
But it only covers areas as you can see, rather than cities such as 'Manchester, Edinburgh' etc.
Any input would be greatly appreciated.
Thanks,
AP
You might think of using Google Map API
You can use the ONS Postcode Directory (ONSPD). You'd have to set up a database and import all the data, then build your application round it.