PHP - create a tournament results order from array - php

Consider I have a following array of total scores, with each value being a score of a player in a tournament.
$total_scores = array(350,200,150,150,75,75,75,0);
I need to create a table, which lists the players with correct positions, if they have the same score, the listing should reflect this, ie.:
1. Player 1 350
2. Player 2 200
3.-4. Player 3 150
3.-4. Player 4 150
5.-7. Player 5 75
5.-7. Player 6 75
5.-7. Player 7 75
8. Player 8 0
I tried to do something with
foreach ($total_scores as $total_score) {
$no_of_occurrences = array_count_values($total_scores)[$total_score];
}
But cannot figure out how to build the correct positions numbering.

<?php
$scores = array(350,200,150,150,75,75,75,0); //assuming you have sorted data otherwise you need to sort it first
$count = array();
$startIndex = array();
$endIndex = array();
$len = count($scores);
for($i = 0; $i < $len; $i++){
if(!isset($count[$scores[$i]])){
$count[$scores[$i]] = 1;
$startIndex[$scores[$i]] = $endIndex[$scores[$i]] = $i+1;
}else{
$count[$scores[$i]]++;
$endIndex[$scores[$i]] = $i+1;
}
}
$i = 1;
foreach($scores as $s){
echo $startIndex[$s].'.';
if($startIndex[$s] != $endIndex[$s]){
echo '-'.$endIndex[$s].'.';
}
echo ' Player '.$i.' '.$s."\n"; //if newline not works try echoing <br>
$i++;
}
Working Demo

For this Array needs to be sorted in descending order
$total_scores = array(350, 200, 150, 150, 75, 75, 75, 0);
rsort($total_scores);
$no_of_occurrence = array_count_values($total_scores);
array_unshift($total_scores, ""); // For starting count from 1
unset($total_scores[0]); // For starting count from 1
$i = 1;
foreach ($total_scores as $key => $value)
{
$position = array_keys($total_scores,$value);
if($no_of_occurrence[$value] == 1)
{
echo "Position " . $i . " ";
echo "Player " . $i . " " . $value . " ";
}
else
{
echo "Position " . $position[0] . " - " . end($position) . " ";
echo "Player " . $i . " " . $value . " ";
}
$i++;
echo "<br>";
}
Output of above code :
Position 1 Player 1 350
Position 2 Player 2 200
Position 3 - 4 Player 3 150
Position 3 - 4 Player 4 150
Position 5 - 7 Player 5 75
Position 5 - 7 Player 6 75
Position 5 - 7 Player 7 75
Position 8 Player 8 0

Related

Assigning Positions to Students, PHP

I am still a novice at PHP scripting.
I have an Array
$students = array(1201=>94,1203=>94,1200=>91, 1205=>89, 1209=>83, 1206=>65, 1202=>41, 1207=>38,1208=>37, 1204=>37,1210=>94);
From the associative array, the key are the student's exam no and the values are the student's scores. Then I used the 2 inbult PHP functions array_keys and array_values to separate the exam nos from the scores.
$exam_nos=(array_keys($students));
$marks=(array_values($students));
Then I passed the $marks array through the code below:
$i=0;
$occurrences = array_count_values($marks);
$marks = array_unique($marks);
echo '<table border="1">';
foreach($marks as $grade) {
if($grade == end($marks))$i += $occurrences[$grade]-1;
echo str_repeat('<tr><td>'.$grade.': '.($i+1).'</td></tr>',$occurrences[$grade]);
$i += $occurrences[$grade];
}
echo '</table><br />';
output:
94: 1
94: 1
94: 1
91: 4
89: 5
83: 6
65: 7
41: 8
38: 9
37: 11
37: 11
And this is closer to what I want; to rank the scores such that if a tie is encountered, 1 or more positions are skipped, occurs at the end the position the items at the end are assigned a position equivalent toi the total number of ranked items. However, it would be much helpful if this could be done without separating the Array into 2 ...
Questions:
(1) I am pulling my hair how, from the $student array I could have something like:
Exam No Score Position
1201 94 1
1210 94 1
1203 94 1
1200 91 4
1205 89 5
1209 83 6
1206 65 7
1202 41 8
1207 38 9
1204 37 11
1208 37 11
(2) I would like to be able to pick any student by exam no and be able to echo or print out her position e.g
the student 1207 is number 9.
I think I need to capture the postions in a variable, but how do I capture them? Well I don't know!
Could the experts help me here with a better way to achieve my 2 goals (please see questions 1 and 2)? I will try any suggestion that will help me disolve the 'metal blockage' I have hit.
If you're pulling out the students from a database (mentioned in the comments), you could retrieve them with the desired format directly using SQL.
However, I'm going to assume that that's not an option. You could do as follows:
$students = array(1201=>94,1203=>94,1200=>91, 1205=>89, 1209=>83, 1206=>65, 1202=>41, 1207=>38,1208=>37, 1204=>37,1210=>94);
arsort($students);// It orders high to low by value. You could avoid this with a simple ORDER BY clause in SQL.
$result = array();
$pos = $real_pos = 0;
$prev_score = -1;
foreach ($students as $exam_n => $score) {
$real_pos += 1;// Natural position.
$pos = ($prev_score != $score) ? $real_pos : $pos;// If I have same score, I have same position in ranking, otherwise, natural position.
$result[$exam_n] = array(
"score" => $score,
"position" => $pos,
"exam_no" => $exam_n
);
$prev_score = $score;// update last score.
}
$desired = 1207;
print_r($result);
echo "Student " . $result[$desired]["exam_no"] . ", position: " . $result[$desired]["position"] . " and score: ". $result[$desired]["score"];
Hope it helps you.
I would use a custom object to process the students individually and store them in an array.
$students = array(1201=>94,1203=>94,1200=>91, 1205=>89, 1209=>83, 1206=>65, 1202=>41, 1207=>38,1208=>37, 1204=>37,1210=>94);
arsort($students); // Sort the array so the higher scores are on top.
$newStudents = array();
$pos = 0;
$count = 0;
$holder = -1; // Assuming no negative scores.
foreach($students as $k=>$v){
$count++; // increment real counter
if($v < $holder || $holder == -1){
$holder = $v;
$pos = $count;
}
$newStudents[] = makeStudent($pos, $v, $k);
// If you want the exam # as the array key.
// $newStudents[$k] = $student;
}
$newStudents = fixLast($newStudents);
// outputs
print_r($newStudents);
foreach($newStudents as $v){
echo "position : " . $v->position . "<br>";
echo "score : " . $v->score . "<br>";
echo "exam : " . $v->exam . "<br>";
}
function makeStudent($pos, $score,$examNo){
$student = new stdClass(); // You could make a custom, but keeping it simple
$student->position = $pos;
$student->score = $score;
$student->exam = $examNo;
return $student;
}
function fixLast($students){
$length = count($students) -1;
$count = 0;
$i = $length;
while($students[$i]->position == $students[--$i]->position){
$count++;
}
for($i = 0; $i <= $count; $i++){
$students[$length - $i]->position = $students[$length - $i]->position + $count;
}
return $students;
}

I am facing a small bump printing number pyramids , still a newbie to php and programming

What i want to print is
1
3 5
7 9 11
With my current code , that is ...
<?php
function Odd($limit='20'){
$c = 1;
while($c <= $limit){
if ($c % 2!=0){
echo $c ;
echo "<br/>";
}
$c++ ;
}
}
Print Odd();
?>
i am getting
1
3
5
7
9
11
Can someone please guide me the right way ?
Aaah ... ok.^^ Now i got it.
Its pretty easy: You need another variable which counts up and one which limits the breakposition. Looks like this:
<?php
function Odd($limit='40'){
$c = 1;
$count = 0;
$break = 1;
while($c <= $limit){
if ($c % 2!=0){
echo $c . " ";
$count++;
if($count === $break) {
echo "<br/>";
$break++;
$count = 0;
}
}
$c++ ;
}
}
Print Odd();
?>
Output till 40:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
31 33 35 37 39
Edit: Code for your new request:
<?php
function Odd($limit='40'){
$c = 1;
$count = 0;
$break = 1;
while($c <= $limit){
echo $c . " ";
$count++;
if($count === $break) {
echo "<br/>";
$break++;
$count = 0;
}
$c++ ;
}
}
Print Odd();
?>
So if I understand correctly you want to output something like that:
1
3 5
7 9 11
13 15 17 19
Here is my solution:
function Odd($limit='20'){
$c = 1;$some_array = array();
while($c <= $limit){
if ($c % 2!=0){
$some_array[]=$c;
}
$c++ ;
}
return $some_array;
}
$array = Odd();
$nr =0;
$j=1;
foreach ($array as $key => $value) {
echo $value.' ';$nr++;
if($nr==$j){
echo '<br />';
$nr=0;
$j++;
}
}
Hope this helps!
From your question it Seems you are really new to programming so before writing any program first of all observe the question properly:
For example for the question above it is clear that is an triangle of odd numbers.
now the number of odd numbers on each row is equal to the row
i.e 1st row contains 1 number ,2nd contains 2 and it continues...
Now what we do is take an variable to count the no of rows say $row and the other will be $limit .
<?php
function odd($limit){
$row=1;
$current_number=1;
while($current_number<=$limit){
for($i=1;$i<=$row;$i++){
echo $current_number." ";
$current_number=$current_number+2;//incrementing numbers by 2 if you want to increment by 1 i.e print all numbers replace 2 by 1
}
$row++;
echo "<br/>";//for new line
}
}
To run above function you need to call it and pass the value of $limit.To do it just type anywhere outside of this function.
odd(20);
Watch this running here:

Counter inside while loop every X times increase

I'm not really sure how to work this question, but I currently have a while loop outputting <li></li>.
Let's say that there are 35 rows and I want the counter to increase every five times.
So the output would be something like this.
- 1 Name
- 1 Name
- 1 Name
- 1 Name
- 1 Name
- 2 Name
- 2 Name
- 2 Name
- 2 Name
- 2 Name
- 3 Name
- 3 Name
- 3 Name
- 3 Name
- 3 Name
- 4 Name and so on...
I've tried counting throughout the loop and comparing the number to see if it was less than five and if not then increasing it, but I know that's not correct. Just can't seem to figure out the best solution.
while ($stmt->fetch()) {
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
To try to make this clearer...basically I would like to have a counter variable running. Starting at 1, but every fifth time through the while loop, I would like to increase this count variable by one.
$count = $rows = 0;
while ($stmt->fetch()) {
if ($rows % 5 == 0)
$count++;
$rows++;
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
You could use array_fill() (psuedo code):
<?php
$li = "<li>Item</li>";
$row = array_fill(0, 5, $li);
$list = array_fill(0, 35, $row);
print_r($list);
?>
http://codepad.org/ETCv3GBK
As in:
$count = 0;
while ($stmt->fetch() && $count++) {
$HTML .= implode('', array_fill(0, 5, "<li data-id='$id' data-name='$name'>$count Name</li>"));
}
Another demo (ignite.io may not be working on save, though):
https://ignite.io/code/514a9bf5ec221ee821000005
for($i=1; $i <= 20; $i++){
$array[] = "Name " . $i;
}
$count = 1;
$output = 1;
for($i=0; $i < 20; $i++){
if($count++ < 5)
echo $output . ". " . $array[$i] . "<BR>";
else{
$count = 1;
echo $output++ . ". " . $array[$i] . "<BR>";
}
}
returns
Name 1
Name 2
Name 3
Name 4
Name 5
Name 6
Name 7
Name 8
Name 9
Name 10
Name 11
Name 12
Name 13
Name 14
Name 15
Name 16
Name 17
Name 18
Name 19
Name 20
$i=1
while ($stmt->fetch()) {
if($i%5==0){
$HTML .= "<li data-id='$id' data-name='$name'>$count Name</li>";
}
$i++;
}

Parallel HTML Rows

I have a HTML table with more than 1000 rows. Now i want to show these records in parallel manner.
Like 30 rows in left side and 30 in right side
1 xyz 120 00:10:01 31 xyz 120 00:10:01
1 xyz 120 00:10:01 32 mxy 20 00:10:01
2 mxy 20 00:10:01 . . . ........
. . . ........ . . . ........
. . . ........ . . . .........
. . . ........ . . . .........
30 mld 2 00:05:01 60 mld 2 00:05:01
I am going to generate PDF so i want to show 60 records per page. 30 left and 30 right.
It will probably be easiest to display two tables side by side (set each to a width of about half the page and float one to the left or right).
Then your loop can be simple:
$i = -1;
$totalRows = count($rows);
$halfRows = round($numRows / 2);
//construct $headerRow HTML here
foreach ($rows as $row) {
$i++;
if ($i == 0 || $i == $halfRows) {
echo '<table class="'. ($i==0 ? 'floatLeft': '').'">';
echo $headerRow;
}
//Code to output column values here
if ($i == ($halfRows - 1)) {
echo '</table>';
}
}
echo '</table>';

display format of input using php

I need to display array of 10 numbers in three columns. if i add another number some like, 11 it must add below 10. as numbers increasing row can be increased not the column, can any one say?
1 4 7 10
2 5 8
3 6 9
am getting 10 in fourth column, but i need it in third column. and row will get increased like
1 4 8
2 5 9
3 6 10
4 7
Display Output in table..
<?php
$arr = array("1","2","3","4","5","6","7","8","9","10", "11", "12", "13");
$row= ceil(count($arr)/3);
echo "<table border='1'>";
for($i = 1; $i <= $row; $i++) {
echo "<tr>";
echo "<td>". $i ."</td>";
$k = 0;
$pre = 0;
for($j = 1; $j <= 2; $j++) {
if($pre == 0)
$pre = $k = $i + $row;
else
$pre = $pre + $row;
if($pre <= max($arr))
echo "<td>". $arr[$pre-1] ."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Output will be:
1 6 11
2 7 12
3 8 13
4 9
5 10
Try this...
<?php
$arr = array("1","2","3","4","5","6","7","8","9","10", "11", "12", "13", "14");
$row= ceil(count($arr)/3);
for($i = 1; $i <= $row; $i++) {
echo $i;
$k = 0;
$pre = 0;
for($j = 1; $j <= 2; $j++) {
if($pre == 0)
$pre = $k = $i + $row;
else
$pre = $pre + $row;
if($pre <= max($arr))
echo " ". $arr[$pre-1] ." ";
}
echo "<br>";
}
?>
Output when 14 element:
1 6 11
2 7 12
3 8 13
4 9 14
5 10
Output when 11 element:
1 5 9
2 6 10
3 7 11
4 8
Output when 13 element:
1 6 11
2 7 12
3 8 13
4 9
5 10

Categories