I want to build a Recommendation system that recommends people base on their preferences towards user details for example if User1 wants someone who is male and lives america, an array would be made of this being User1{male, america} while the second array would be the other users details for example user2 being female and from america her array would be User2{female, america}, user 3 being {male, america} I want to be able to find the similarity distance between user 1 and the other users array and base on the score it would be listed from the highest to the lowest.
The dirty way of doing it:
foreach($item in $array_one){
foreach($item_two in $array_two){
if($item == $item_two){
echo "Euston, we found a match!";
}
}
}
The clean way of doing it:
$intersection = array_intersect($array_one, $arrary_two);
if (in_array($value_to_look_for, $intersection)) {
echo "Euston, we have a match!";
}
Related
I'm working on a project with laravel and I have to ask to database some queries that have to return an array. This is the code that I have
Logged as a teacher:
$teacher= Teacher_Admin::where('id_user', Auth::user()->id)->first();
$grades = Grade::where('id_depar', $teacher->id_depar)->get(); //3 grades
$studients_grades = Studient_Grades::where('id_grade', $grades->id)->get(); //5 studient
$studients = Studient::where('id', $studients_grades->id_studient)->get(); //5 studient
$user = User::where('range', 2)->get();//5 users
What I'm trying to do is look for all the studients that are enrolled on a grade that is on the department of the teacher, e.g. Departments: IT, Chemistry. In IT department we have two Grades: Frontent Development and Backend Development. And I have 30 studient per grade. How I can get the 60 studients?
If you need more code please ask, this is my first question and I'm not sure how to do this
Thanks in advice
Finally I got it. When I start receiving get() answers, it returns a multiple array so I have to parse to something like this
$teacher= Teacher_Admin::where('id_user', Auth::user()->id)->first();
$grades = Grade::where('id_depar', $teacher->id_depar)->get();
$id_grades = []
foreach ($grades as $grade){
$id_grades = $grade->id
}
$studients_grades = Studient_Grades::whereIn('id_grade', $id_grades)->get();
I was able to work with this :) Hope to help someone someday
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'm looking for retrieve all of the friends who use the same app (PHP SDK 4.), with the uid,username, and score
I have this permission for my app:
('email', 'user_about_me', 'user_friends', 'publish_actions',
'user_games_activity')
now, I'm working with this script that retrive just the uid of the user who use the same app:
$me = (new \Facebook\FacebookRequest($session, 'GET', '/me/friends'))->execute()->getGraphObject(\Facebook\GraphUser::className());
$result = $me->asArray();
// Get user's friends
$friends = $result['data'];
// Converting classes to array
foreach ($friends as $key => $value) {
$friends[$key] = (array)$value;
echo $friends[0]['id']; //show the id of the user 0
echo "|";
}
and I have a problem just for check all of the friends, I try to change this script, but I can't get all friends, but just the first one... [0]
now, I search a lot about this topic... but I find just for the old SDK, with a new, what I should do to retrive the uid,username and score of the same app? like this:
echo $friends[0]['id']; //show the id of the user 0
echo "|";
echo $friends[0]['name']; //show the name of the user 0
echo "|";
echo $friends[0]['score']; //show the score of the user 0
echo "|";
[number_uid0] | [nameusername0] | [score0] | [number_uid1] | [nameusername1] | [score1] etc....
Thank you very much :)
You can't get ALL friends anymore, only those which also use your app. And all friends_* permissions have been removed, so you can't simply retrieve your friends' scores...
But have a look here to find a solution to (what I think is) your problem:
https://developers.facebook.com/docs/games/scores#read-many-scores
You can read the set of scores for a player and their friends by issuing an HTTP GET request to /APP_ID/scores with the user access_token for that app. The user_friends permission is required in order to view friends' scores. This returns a list of scores for a player and friends who have authorized the app. The list is sorted by descending score value, so it returns friends with the highest scores first. You can use this call to generate a leader board for a player and friends.
I have a bunch of data in array without sorting, i need to categorize the data into set and display to the public. This is how the data loop without categorisation.
foreach ($info as $i){
if ($i->metadataKey==1018){
echo $i->businessId . " - " . $i->businessName . " - " . $i->metadataValue;
}
if ($i->metadataKey==1021){
echo ", " . $i->metadataValue;
echo "<br/>";
}
}
it's a joined table and one business having numbers of metadata (associated by metadataKey and metadataValue). The following is the code i getting data from database.
$info = DB::table('business')
->leftJoin('business_meta', 'business.Id', '=', 'business_meta.businessId')
->get();
Or you may reference the following table
Business
id
business name
Business_meta
metadatakey
metadatavalue
businessId
one business will have couple of business meta, 1018 is state and 1021 is country
I need to assorciate it into sort array or some pattern of data to display it according to "state, country" on the public site.
Which mean, it may be something like
California, US
Business 1
Business 2
Texas, US
Business 3
Please advice how can i make it. Thanks.
I think usort is all you need. Just create your custom function for sorting both levels of your array.
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.