Need advise generating data-tables - php

Working in Zend framework and using Doctrine.
I have 1 competition, concisting of several matches ( could be from as little as 4 up to as much as 50 ).
These matches usually have the same players in them.
I have the tables:
Competitions
Matches
Matchresults
Users
First step, get all matches belong to competition, this is easy, so no worries there.
Now it gets tricky:
Step two, get all results of said matches, still ok, i can get the data, but presenting this data is the challenging part.
Step three, get the names from the users table, where the users id is equal to the users id given in the matchresults table.
The end result should be a table looking something like this.
Name Match1 match2 match3 total points
firstname + lastname 50 60 61 171
firstname + lastname 52 56 66 174
I can get all the data correctly, but getting it all in the right field is a bit of a problem.
Could anyone point me in the right direction or maybe give me an example?
Cheers,
Mark
EDIT: clarification.
This is for a fishing competition.
Each match has an x amount of fisherman and these get points according to what they catch.
The calender year has been divided into competitions, 2 or 4, can be different each year.
These matches have a begin-date and an end-date and all matches that have been played in between the begin date and end date of a competition, belong to that competition.
Now the user of the app, wants to make an excell export, showing all the results in the manner i've shown above, the more matches, the more columns with points in them.

You want to make yourself a function which transforms a competition into a list of users along with their results. Something like:
public function transform($competition)
{
$users = array();
$matches = $competition->getMatches();
$matchCount = count($matches);
$matchNum = 0;
foreach($matches as $match)
{
$matchNum++;
foreach($match->getResults() as $result)
{
$user = $result->getUser();
$userId = $user->getId();
// Add new user if necessary
if (!isset($users[$userId]))
{
// Store the name
$users[$userId]['name'] = $user->getFirstName() . ' ' . $user->getLastName();
// Spot to store total points
$users[$userId]['total'] = null;
// Individual match results
$users[$userId]['matches'] = array();
// Spots for each match in case users skip a match
for($i = 1; $i <= $matchCount; $i++) $users[$userId]['matches']['Match' . $i] = null;
}
$points = $result->getPoints();
$users[$userId]['matches']['Match' . $matchNum] = $points;
$users[$userId]['total'] += $points;
}
}
// Use usort if you want to sort by names
// Done
var_dump($users);
return $users;
}

Related

php array_push not functioning

I have a script i'm working on thats automaticly building team pools. There is several clubs and each club can have multiple teams. Multiple teams in one pool from the same club are not allowed. This is where my script goes wrong. It checks if the team is in the same club that the other teams in the same pool (16 pools,4 teams per pool).
It pops the teamid from an array and compares club ID's in DB, if they have same club ID the teamID gets pushed back into the array and repeats untill it finds team in different club.
Somehow it(sometimes?) fails to push the team back into array and i cannot see what i have done wrong. Is this happens once, i end up with a team less, if it happens more then once, the last(or2 last) pools have empty value's wich will cause the while loop to go forever.
This is a code snippet that compares the team and club ID's.
//TeamA
//set dummyteam if needed, else choose from array
if($dummy != 0){
$teamA = "73";
--$dummy;
}
else{
$teamA = array_pop($teams);
}
$teamB = array_pop($teams);
//TeamB
//is TeamB in different club then Team A?
$ABteamisdifferent = 0;
while($ABteamisdifferent == 0){
if(GetClubID($teamA) == GetClubID($teamB)){
$teams[] = $teamB;
shuffle($teams);
$ABteamisdifferent = 0;
$teamB = array_pop($teams);
}
else{
$ABteamisdifferent = 1;
}
}
......
Full code link
Script output
Function Code
I've wasted 3 hours trying to fix this, but i'm probably overlooking something stupid. Still, any help is greatly appreciated.
You're adding the team back into a $team variables instead of $teams. Simply change the following line:
$team[] = $teamB;
to:
$teams[] = $teamB;

I need some help creating a query and a database table to retroactively assign numbers to existing table

As my info states, I inherited the job of statistician for a local dart league. (Woohoo $20 a season)
I would love to implement an ELO rating system.
The current database table has over 100,000 entries.
There are 3 different games that are played. Singles, Doubles, and Team.
The originator of the database has the games entered as such:
Index Player1_num Player2_num Opp_Player1_num Odd_Player2_num H_team V_team Season Week W L Game_type
A singles game is entered twice.
values(1,20,null,30,null,200,300,11,2,1,0,301_singles)
and
values(2,30,null,20,null,200,300,11,2,0,1,301_singles)
It was done this way to facilitate easier look-ups of individuals.
A doubles game would have values such as
(3,20,21,30,31,200,300,11,2,1,0,501_doubles)
(4,21,20,30,31,200,300,11,2,1,0,501_doubles)
(5,30,31,20,21,200,300,11,2,0,1,501_doubles)
(6,31,30,20,21,200,300,11,2,0,1,501_doubles)
There again, it is built for easier queries for looking up wins and losses across seasons and with different partners.
A team game is:
(7,null,null,null,null,200,300,11,2,1,0,team_game)
So I added a match_num column to the table to help lump the games under 1 number.
However, I am unsure how best to assign the numbers, understandably, I don't feel like going through all 90k entries by hand.
Note: The early seasons were modified by hand and not all double matches have 4 entries (some only have 1). Some matches may be out of order as well (Instead of indexes: 1,2 they could be 1,9).
I don't know if you need more info for this, and I am unsure of how to post larger examples of the table.
Current code:
<body>
<?php
include "inc.php";
// Select Max Match Number
$sqlMatch="select max(match_num) from stats_results";
$match =mysql_query($sqlMatch);
$m= $match ? mysql_result($match,0):mysql_error();
$matchno= $m+1; // First Match number
$game=array("'301_singles'","'cricket_singles'","'501_singles'","'301_doubles'","'cricket_doubles'");
// selects max season
$sqlSeason="select max(season_index) from stats_season";
$season =mysql_query($sqlSeason);
$smax= $season ? mysql_result($season,0):mysql_error();
# $smax=2;
// for each season up to max season
for($s=1;$s<=$smax;$s++)
{
// Selects max week within the current season
$sqlWeek="select max(week) from stats_results where season=$s ";
$Week =mysql_query($sqlWeek);
$wmax= $Week ? mysql_result($Week,0):mysql_error();
# $wmax=2;
// for each week within current season up to the max week
for ($w=1;$w<=$wmax;$w++)
{
// each singles game
foreach($game as $g)
{
###########################################################################################################
$result = mysql_query("SELECT * FROM stats_results where season=$s and week=$w and game_code=$g ;") or die(mysql_error());
// Put them in array
for($i = 0; $rows[$i] = mysql_fetch_assoc($result); $i++) ;
// Delete last empty one
array_pop($rows);
//******************************************************
$matches=array();
foreach($rows as $record)
{
// Get a unique match code for this match
$matchid= getMatchID($record);
// Have we seen this ID before? If yes add this record index to the existing array
// otherwise create an array with just this value
if (!isset($matches[$matchid])) $matches[$matchid]= array($record['index_results']); // No
else $matches[$matchid][]= $record['index_results']; // Yes, add this Index
}
// Now $matches is an array of arrays of Index values, grouped by "match" so...
/* Sort $matches by key (see getMatchID for why!) */
ksort($matches);
// Update the table
foreach($matches as $match)
{
// Create SQL instruction to set the match_num for all the Index values in each entry
$sql= "UPDATE stats_results SET match_num = $matchno WHERE index_results IN (".implode(",", $match).")";
echo "<br>";
echo $sql;
/* Execute the SQL using your chosen method! */
// Move the match count on
$matchno++;
}
// End our loops
}
}
}
function getMatchID($gamerecord)
{
$index= "{$gamerecord['season']}-{$gamerecord['week']}-{$gamerecord['game_code']}-";
$players= array(
$gamerecord['player1_num'],
empty($gamerecord['player2_num'])?0:$gamerecord['player2_num'],
$gamerecord['opp_player1_num'],
empty($gamerecord['opp_player2_num'])?0:$gamerecord['opp_player2_num']
);
// Sort the players to get them in a consistent order
sort($players);
// Add the sorted players to the index
$index.= implode('-', $players);
return $index;
}
?>
</body>
(I'm putting this into an Answer so I can get it to layout a bit better - but it's not really a "solution" as such!)
I think what I'd do is try and build an array of arrays of Index values grouped by game - you can then use that to create SQL to update the table.
So, if $rows is an array of all records we'd do something like the following pseudo-code:
$matches= array();
foreach($rows as $record)
{
// Get a unique match code for this match
$matchid= getMatchID($record);
// Have we seen this ID before? If yes add this record index to the existing array
// otherwise create an array with just this value
if (!isset($matches[$matchid])) $matches[$matchid]= array($record['Index']); // No
else $matches[$matchid][]= $record['Index']; // Yes, add this Index
}
// Now $matches is an array of arrays of Index values, grouped by "match" so...
/* Sort $matches by key (see getMatchID for why!) */
ksort($matches);
// Update the table
$matchno= 1; // First Match number
foreach($matches as $match)
{
// Create SQL instruction to set the match_num for all the Index values in each entry
$sql= "UPDATE games SET match_num = $matchno WHERE Index IN (".implode(",", $match).")";
/* Execute the SQL using your chosen method! */
// Move the match count on
$matchno++;
}
So all that leaves is the getMatchID function - if we give each match a temporary ID based on it's season, week and a sorted list of it's participants (and use the Season and Week first) that should be unique for each game and we can sort by this index later to get the games in the right order. So again in rough pseudo-code, something like:
function getMatchID($gamerecord)
{
$index= "{$gamerecord['Season']}-{$gamerecord['Week']}-{$gamerecord['H_Team']}-{$gamerecord['V_Team']}-";
$players= array(
empty($gamerecord['Player1_Num'])?0:$gamerecord['Player1_Num'],
empty($gamerecord['Player2_Num'])?0:$gamerecord['Player2_Num'],
empty($gamerecord['Opp_Player1_Num'])?0:$gamerecord['Opp_Player1_Num'],
empty($gamerecord['Opp_Player2_Num'])?0:$gamerecord['Opp_Player2_Num']
);
// Sort the players to get them in a consistent order
sort($players);
// Add the sorted players to the index
$index.= implode('-', $players);
return $index;
}
So all being well $index would come back with something like 11-2-200-300-0-0-20-30 for the first singles match in your example - no matter which of the game records we were looking at.
Does that make sense/help at all?

Using Inner Join and mysql_num_rows() is Always returning 1 less row

I checked throught the existing topics. I have a fix for my problem but I know its not the right fix and I'm more interested making this work right, than creating a workaround it.
I have a project where I have 3 tables, diagnosis, visits, and treatments. People come in for a visit, they get a treatment, and the treatment is for a diagnosis.
For displaying this information on the page, I want to show the patient's diagnosis, then show the time they came in for a visit, that visit info can then be clicked on to show treatment info.
To do this a made this function in php:
<?
function returnTandV($dxid){
include("db.info.php");
$query = sprintf("SELECT treatments.*,visits.* FROM treatments LEFT JOIN visits ON
treatments.tid = visits.tid WHERE treatments.dxid = '%s' ORDER BY visits.dos DESC",
mysql_real_escape_string($dxid));
$result = mysql_query($query) or die("Failed because: ".mysql_error());
$num = mysql_num_rows($result);
for($i = 0; $i <= $num; ++$i) {
$v[$i] = mysql_fetch_array($result MYSQL_ASSOC);
++$i;
}
return $v;
}
?>
The function works and will display what I want which is all of the rows from both treatments and visits as 1 large assoc. array the problem is it always returns 1 less row than is actually in the database and I'm not sure why. There are 3 rows total, but msql_num_rows() will only show it as 2. My work around has been to just add 1 ($num = mysql_num_rows($result)+1;) but I would rather just have it be correct.
This section looks suspicious to me:
for($i = 0; $i <= $num; ++$i) {
$v[$i] = mysql_fetch_array($result MYSQL_ASSOC);
++$i;
}
You're incrementing i twice
You're going to $i <= $num when you most likely want $i < $num
This combination may be why you're getting unexpected results. Basically, you have three rows, but you're only asking for rows 0 and 2 (skipping row 1).
Programmers always count from 0. So, you are starting your loop at 0. If you end at 2, you have reached 3 rows.
Row0, Row1, Row2.
if $i = 0, and u increment it BEFORE adding something to the array, u skip the first row. increment $i AFTER the loop runs to start at 0 (first key).
For loops are not good for this: rather do:
$query=mysql_query(' --mysql --- ');
while ($row=mysql_fetch_array($query)){
$v[]=$row["dbcolumn"];
}
return $v for your function then.compact and neat. you can create an associative array, as long as the key name is unique (like primary ids).. $v["$priid"]=$row[1];

Get a random number betwen 1-200 but leaves out numbers read from query

I need to get a random number between, lets say 1-200, but at the same time I need to prevent selecting a random number that has already been used for a particular REMOTE_ADDR (as stored in a table).
This is what I have so far (I have tried several different approaches):
$ip = $_SERVER['REMOTE_ADDR'];
$query7 = "
SELECT *
FROM IP
WHERE IP = '$ip'
";
$result7 = mysql_query($query7) or die(mysql_error());
$rows7 = mysql_num_rows($result7);
while ($row7 = mysql_fetch_array($result7)){
$id = $row7['ID'];
}
I'm using the random number to pick an image to display, but my users are complaining that the images selected for them is not random enough; ie, the same picture is getting "randomly" selected too often, sometimes showing the same image over and over.
It does not have to be in PHP, if there is another option.
Something like that
// all ids from 1 to 100
$all = array_fill(1, 200, 0);
// remove used
foreach ($used as $i) {
unset($all[$i]);
}
// get survived keys
$keys = array_keys($all);
// get random position, note that the array with keys is 0 based
$j = rand(0, count($all) - 1);
return $keys[$j];
Run your select and instead of using *, only select the id column. Then use:
while($row7[] = mysql_fetch_array($query7));
do{
$rand = rand(0,200);
}while(in_array($rand,$row7));
You can do it all in mysql. Have one table that has your list of images, and another table that has the list of IP addresses and the images that have already been shown to that IP. Then you select and join the tables and order the result randomly.
SELECT image_id FROM images
LEFT JOIN shown_images ON images.image_id=shown_images.image_id AND ip_addr=[#.#.#.#]
WHERE shown_images.image_id IS NULL
ORDER BY RAND() LIMIT 1;
After you show an image to an IP, just insert a record into the shown_images table with the IP and the image ID. That will work right up until that have seen all the images. Then you can delete the records and start over.
This answer assumes that you have 200 items, and collect the items which you do not want to show. Alternatively, you can query only id's of available items and choose from these, you would need to create a table with available items for that.
Create a map which maps consecutive numbers to (non-consecutive) available numbers. Suppose the numbers 1 and 3 are in use, you can map to 2 and 4 (and so on).
Actually, it is possible to use a simple array (not-associative) for this. You can do something like this:
$reserved = array(1, 3); // fill $reserved using your code
$available = array();
for ($i = 1; $i <= 200; $i++) {
if (!in_array($i, $reserved)) {
$available[] = $i;
}
}
if (count($available) > 0) {
$random_index = rand(0, count($available) - 1);
$r = $available[$random_index];
} else {
// Nothing available!
}
There will be nothing to choose when you run out of pictures that have not been displayed yet. In this case, count($available) will be zero. One way to solve this would be to clear your list of displayed images for the current IP and choose again; see also other answers for this.

How can I select a PHP variable that relates to a specific percentage chance?

I'm trying hard to wrap my head around what I'm doing here, but having some difficulty... Any help or direction would be greatly appreciated.
So I have some values in a table I've extracted according to an array (brilliantly named $array) I've predefined. This is how I did it:
foreach ($array as $value) {
$query = "SELECT * FROM b_table WHERE levelname='$value'";
$result = runquery($query);
$num = mysql_numrows($result);
$i=0;
while ($i < 1) {
$evochance=#mysql_result($result,$i,"evochance"); // These values are integers that will add up to 100. So in one example, $evochance would be 60, 15 and 25 if there were 3 values for the 3 $value that were returned.
$i++;
}
Now I can't figure out where to go from here. $evochance represent percentage chances that are linked to each $value.
Say the the favourable 60% one is selected via some function, it will then insert the $value it's linked with into a different table.
I know it won't help, but the most I came up with was:
if (mt_rand(1,100)<$evochance) {
$valid = "True";
}
else {
$valid = "False";
}
echo "$value chance: $evochance ($valid)<br />\n"; // Added just to see the output.
Well this is obviously not what I'm looking for. And I can't really have a dynamic amount of percentages with this method. Plus, this sometimes outputs a False on both and other times a True on both.
So, I'm an amateur learning the ropes and I've had a go at it. Any direction is welcome.
Thanks =)
**Edit 3 (cleaned up):
#cdburgess I'm sorry for my weak explanations; I'm in the process of trying to grasp this too. Hope you can make sense of it.
Example of what's in my array: $array = array('one', 'two', 'three')
Well let's say there are 3 values in $array like above (Though it won't always be 3 every time this script is run). I'm grabbing all records from a table that contain those values in a specific field (called 'levelname'). Since those values are unique to each record, it will only ever pull as many records as there are values. Now each record in that table has a field called evochance. Within that field is a single number between 1 and 100. The 3 records that I queried earlier (Within a foreach ()) will have evochance numbers that sum up to 100. The function I need decides which record I will use based on the 'evochance' number it contains. If it's 99, then I want that to be used 99% of the time this script is run.
HOWEVER... I don't want a simple weighted chance function for a single number. I want it to select which percentage = true out of n percentages (when n = the number of values in the array). This way, the percentage that returns as true will relate to the levelname so that I can select it (Or at least that's what I'm trying to do).
Also, for clarification: The record that's selected will contain unique information in one of its fields (This is one of the unique values from $array that I queried the table with earlier). I then want to UPDATE another table (a_table) with that value.
So you see, the only thing I can't wrap my head around is the percentage chance selection function... It's quite complicated to me, and I might be going about it in a really round-about way, so if there's an alternative way, I'd surely give it a try.
To the answer I've received: I'm giving that a go now and seeing what I can do. Thanks for your input =)**
I think I understand what you are asking. If I understand correctly, the "percentage chance" is how often the record should be selected. In order to determine that, you must actually track when a record is selected by incrementing a value each time the record is used. There is nothing "random" about what you are doing, so a mt_rand() or rand() function is not in order.
Here is what I suggest, if I understood correctly. I will simplify the code for readability:
<?php
$value = 'one'; // this can be turned into an array and looped through
$query1 = "SELECT sum(times_chosen) FROM `b_table` WHERE `levelname` = '$value'";
$count = /* result from $query1 */
$count = $count + 1; // increment the value for this selection
// get the list of items by order of percentage chance highest to lowest
$query2 = "SELECT id, percentage_chance, times_chosen, name FROM `b_table` WHERE `levelname` = '$value' ORDER BY percentage_chance DESC";
$records = /* results from query 2 */
// percentage_chance INT (.01 to 1) 10% to 100%
foreach($records as $row) {
if(ceil($row['percentage_chance'] * $count) > $row['times_chosen']) {
// chose this record to use and increment times_chosen
$selected_record = $row['name'];
$update_query = "UPDATE `b_table` SET times_chosen = times_chosen + 1 WHERE id = $row['id']";
/* run query against DB */
// exit foreach (stop processing records because the selection is made)
break 1;
}
}
// check here to make sure a record was selected, if not, then take record 1 and use it but
// don't forget to increment times_chosen
?>
This should explain itself, but in a nutshell, you are telling the routine to order the database records by the percentage chance highest chance first. Then, if percentage chance is greater than total, skip it and go to the next record.
UPDATE: So, given this set of records:
$records = array(
1 => array(
'id' => 1001, 'percentage_chance' => .67, 'name' => 'Function A', 'times_chosen' => 0,
),
2 => array(
'id' => 1002, 'percentage_chance' => .21, 'name' => 'Function A', 'times_chosen' => 0,
),
3 => array(
'id' => 1003, 'percentage_chance' => .12, 'name' => 'Function A', 'times_chosen' => 0,
)
);
Record 1 will be chosen 67% of the time, record 2 21% of the time, and record 3 12% of the time.
$sum = 0;
$choice = mt_rand(1,100);
foreach ($array as $item) {
$sum += chance($item); // The weight of choosing this item
if ($sum >= $choice) {
// This is the item we have selected
}
}
If I read you right, you want to select one of the items from the array, with some probability of each one being chosen. This method will do that. Make sure the probabilities sum to 100.

Categories