I am building a leaderboard (scorebored) for a poker tournament. My aim is to echo data to a table to display scores for the season and scores all time. I want the table to run in order with the highest season points at the top.
I am getting an error message that reads:
Notice: Undefined index: season in C:\wamp\www\UPT Site\leaders.php on line 11
When I print_r an array from the $allplayers array, it shows that all the players arrays are going in correctly, including the [season] key and value declared on line 6 in the bit below...
Can anyone please tell me how to fix my code? (note, the real code doesn't have line numbers in it, I just added them here to make discussion easier).
1 foreach($allplayers as $player){
2 $i = $player[1];
3 if (${"seasonplayerid" . $i}){
4 $sum = array_sum(${"seasonplayerid" . $i});}
5 //$sum = points this season.
6 ${"playerid" . $i}['season'] = $sum;
7 }
8 function val_sort($array,$key) {
9 //Loop through and get the values of our specified key
10 foreach($array as $k=>$v) {
11 $b[] = strtolower($v[$key]);
12 }
13 asort($b);
14 /* foreach($b as $k=>$v) {
15 $c[] = $array[$k];
16 }return $c;
17 */
18 }
19 $sorted = val_sort($allplayers, '[season]');
20 foreach($allplayers as $player){
21 $i = $player[1];
22 echo ("<tr><td>" . $player[0] . $t . ${"playerid" . $i}[3] . $t . ${"playerid" . $i}[4] . $t. ${"playerid" . $i}['season'] . $t. count(${"seasonplayerid" . $i}). "</td><tr>");
23 }
Here is the print_r output for array $playerid1:
Array ( [0] => Jonathan Thompson [1] => 1 [2] => 2015-S 3 [3] => 944 [4] => 7 [season] => 470 )
Here is a key of the information in the array:
/*
$allplayers is a multidimentional array, containing many arrays of players called $playerid1, $playerid2, $playerid3 etc
playerid1[0] = Player name
playerid1[1] = Player ID
playerid1[2] = Current season
playerid1[3] = total points earned
playerid1[4] = total games played games
playerid1[season] = points earned in current season
*/
Looks like at line 19 you are trying to pass key in second parameter but defined it incorrectly.So, to call function val_sort($array,$key) you have to do something like that.
Therefore at line 19 change
$sorted = val_sort($allplayers, '[season]');
to
$sorted = val_sort($allplayers, 'season');
Also i suggest you to use data table it is good and fast
Instead of below line
$sorted = val_sort($allplayers, '[season]');
you should pass the key as below
$sorted = val_sort($allplayers, 'season');
Hope this helps.
I did a dodgy quick fix in this instance.
I wrote a loop to array_pop each array inside the main array, and created a new variable for each piece of data as the array_pop loop was going.
I also array_pushed the data I wanted to sort by and an ID number to a new array.
I used rsort to sort the new array, then looped through it using the ID number to reconstruct a 3rd array in the order I wanted to output data.
Next time I will take the advice of #rocky and do a data table. I may even go back to redo this page as a data table. To be honest, I'd never heard of a data table before yesterday. Once I've given this project over to the boss I'll be investing my time in learning about data tables and AJAX.
Thank you all for your tips, but the quick fix will have to do this time as I am time poor (This site needs to be live tomorrow morning).
Related
I came across this program on http://www.programmr.com . And the question is
Complete the program to print the sum of negative numbers, positive even numbers, positive odd numbers from a list of numbers entered by the user. The list terminates when the number entered is zero . And my code is,
$nums = array();
while(trim(fgets(STDIN)) != 0){
array_push($nums,trim(fgets(STDIN)));
}
I know the code is incomplete but what im trying to do is to push the inputs to the array and then calculate the sum. When I print_r($nums) the array it gives me this,
Array
(
[0] => 34
[1] => 32
[2] => 45
[3] => 0
)
And my input is,
12
34
12
32
12
45
12
0
0
It pushes the alternative elements i dont know whats happening with this. Please help me , thanks in advance.
You are calling fgets(STDIN) twice in your code, i have adjusted it a bit so the array part is working. The rest of the assignment i let you figure that part out ;) Hint: Use modulus operator.
$nums = array();
do {
$number = (int) trim(fgets(STDIN));
array_push($nums,$number);
} while ($number !== 0);
print_r($nums);
Also if you are using PHP5.6 or higher you can use short array syntax like so:
$nums = [];
And
$nums[] = $number;
I have an array that is like this:
Array{
10 - 2011 Headlight Assembly Nissan Versa
11 - LH 07-11 INS QTLY O.E.M - FREE SAME DAY SHIPPING
12 - 000
13 - A0
14 - 40626A1
15 - $165 actual
16 - More Desc Stuff
}
that is produced from a simple dom result. There are multiple items within the list. What I would like to do is reset the key back to 10 after 17 is reached so that I can loop over all the results within the array and find the proper values without having to look for say keys 10, 14, 15 - and then keys 20, 24, 25, etc.
Not quite sure if I have explained it correctly, or how to accomplish it. Any guidance is appreciated. Thanks in advance!
Well, for the indexes to deny I suggest you tu use an array of these indexes. and to loop through this array from 10 to 16 and then come back to 10, I suggest you to do this
$indexes_to_deny = [14,15,16];
$index = 10;
while( condition to stop the loop )
{
if($index%17===0)
$index = 10;
if(in_array($index,$indexes_to_deny))
{
$index++;
continue;
}
/*
your code here
you can access the items inside the array with $array[$index]
*/
$index++:
}
My solution was to use array_slice to drop off the unnecessary items and then array_chuck the rest and finally just drop the rest at a break point.
I have a bunch of data from a football team that needs tidying up. Currently, it looks like this (for demonstration purposes, I've only included 3):
1
Team One
9 7 1 1 31 13 18 22
2
Team Two
9 6 2 1 25 21 4 19
3
Team Three
9 4 3 2 26 18 8 14
For clarity, I'll deconstruct the first 3 lines:
1\t\n
Team One\n
9\t7\t1\t1\t31\t13\t18\t22
Notice how there is a tab and then a linebreak after the position of each team. Then, the team name on the next line, with just a linebreak. And then finally, all of the details about that team. Then the next team's stats start.
I need it to be converted to:
1,Team One,9,7,1,1,31,13,18,22
2,Team Two,9,6,2,1,25,21,4,19
3,Team Three,9,4,3,2,26,18,8,14
Each line starts with the team's position, then team name, then each stat -- all separated by commas.
I've attempted doing this with very little luck. I imagine some kind of fancy regex can do the trick, but I wouldn't know how... hopefully someone can help!
You can use
$in = file("log.txt");
$out = fopen("php://output", "w");
foreach(array_chunk($in, 3) as $group) {
$group = array_map("trim", $group);
$group[2] = implode(",", str_getcsv($group[2], "\t"));
fputcsv($out, $group);
}
Output
1,"Team One","9,7,1,1,31,13,18,22"
2,"Team Two","9,6,2,1,25,21,4,19"
3,"Team Three","9,4,3,2,26,18,8,14"
If you want empty enclosure then use
fputcsv($out, $group, ",", " ");
Output
1, Team One , 9,7,1,1,31,13,18,22
2, Team Two , 9,6,2,1,25,21,4,19
3, Team Three , 9,4,3,2,26,18,8,14
<?php
$resultstr = array();
foreach($Teams as $items){
$resultstr[] = $items['Team One'];
}
$items = implode(", ",$resultstr);
echo $items;
?>
something like that. You can edit it with your own data because you did not mention that in your question.
I want to construct an array of 3 offers that output in a random order. I have the following code and whilst it does output 3 random offers it doesn't appear to be random. The first value in the generated array always seems to be from the 1st 2 records in my offers table. The offers table only has 5 records in it (I dont know if this is affecting things).
$arrayOfferCount = $offerCount-1;
$displayThisManyOffers = 3;
$range = range(0, $arrayOfferCount);
$vals = array_rand($range, $displayThisManyOffers);`
Any help or advice would be appreciated.
Working fine here. Benchmark it over lots of runs instead of just gut feeling... here it is for 1,000 tries:
<?php
$offerCount = 5;
$arrayOfferCount = $offerCount-1;
$displayThisManyOffers = 3;
$range = range(0, $arrayOfferCount);
for($i = 0; $i < 1000; $i++) {
$vals = array_rand($range, $displayThisManyOffers);
foreach($vals as $val) {
$counts[$val]++;
}
}
sort($counts);
print_r($counts);
Generates:
Array
(
[0] => 583
[1] => 591
[2] => 591
[3] => 610
[4] => 625
)
I know that mt_rand() is much better PRNG.
However, in your case you need to let the database select them for you
SELECT * FROM ads ORDER BY RAND() LIMIT 0, 3
It is probably randomly picking which to display, but displaying them in the same order they appear in your array. If you do it enough times (~20) you should get the third one to show up once if this is the case (chances of choosing exactly the last 3 out of 5 would be 1 in 5*4, so around every 20th one you'll see the third option appear).
array_rand seems not to work properly sometimes (see PHP-Manual comments).
Workaround: Get the array size and pick a random index using the function mt_rand
I need to generate sequences of games using the round robin algorithm. I have the php page where the user can input the tournament name which will be inserted into the database and it has got a drop down menu up to 32 teams (select number of teams).
So if I select 4 teams in the page, so it will be from team 1 to team 4 which would be 6 matches because every team plays the other team once. I know how the algorithm works but I am not quite sure how to write the query for that.
I created the table team:
Team_id 01 02 03 etc
Team_name Team1 Team2 Team3 etc.
What should I do from here?
I created a roundrobin function from scratch as i thought it might be easier to get the same results and also allowing me to use arrays filled with strings directly instead of numbers.
Because i pull a list of names from a database and add into an array i can now schedule this directly with below function. No extra step needed to link numbers to names etc.
Please feel free to try it and if it works then leave a comment.
I also have a version which allows for 2 way (home & return) schedule and or shuffle option. If somone is interested in that one then leave a coment as well.
<?php
/**
* #author D.D.M. van Zelst
* #copyright 2012
*/
function scheduler($teams){
if (count($teams)%2 != 0){
array_push($teams,"bye");
}
$away = array_splice($teams,(count($teams)/2));
$home = $teams;
for ($i=0; $i < count($home)+count($away)-1; $i++){
for ($j=0; $j<count($home); $j++){
$round[$i][$j]["Home"]=$home[$j];
$round[$i][$j]["Away"]=$away[$j];
}
if(count($home)+count($away)-1 > 2){
array_unshift($away,array_shift(array_splice($home,1,1)));
array_push($home,array_pop($away));
}
}
return $round;
}
?>
How to use, for example create an array like:
<?php $members = array(1,2,3,4); ?>
or
<?php $members = array("name1","name2","name3","name4"); ?>
then call the function to create your schedule based on above array:
<?php $schedule = scheduler($members); ?>
To display the resulted array schedule simply do like below or anyway you like:
This little code displays the schedule in a nice format but use it anyway you like.
<?php
foreach($schedule AS $round => $games){
echo "Round: ".($round+1)."<BR>";
foreach($games AS $play){
echo $play["Home"]." - ".$play["Away"]."<BR>";
}
echo "<BR>";
}
?>
Leave a note if it worked for you or if you are interested in the 2-way version with shuffle.
There is a fairly simple algorithm for doing round-robin matchups, my solution would be as follows (in pseudo-code):
fetch all the teams out of the database into an array, in any order
for (i = 1; i < number of teams; i++)
print matchups for Round #i:
the teams in the first half of the array are matched up in the same order with the teams in the last half of the array. That is, the team at any index [n] is matched up with the team at index [n + half the number of teams]. If you have 32 teams, [0] is matched with [16], [1] with [17], etc up to [15] and [31].
Now, "rotate" the teams through the array, but leave the first one in the array in place. That is, [1] becomes [2], [2] becomes [3], ..., up to [31] becomes [1], but do not move the team at index [0].
And that's it, that will produce all the matchups you need.
An example, with 4 teams:
First half of the array is on top, second half is on the bottom, match-ups are numbers above/below each other. Array indexes (to illustrate what I mean exactly):
[0] [1]
[2] [3]
Round 1:
1 2
3 4
Round 2:
1 4
2 3
Round 3:
1 3
4 2