Top List with three parts - php

I have this cod for my TOP LIST
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
data[1] is NAME
data[2] is SURNAME
sms[vote] is NUMBER OF VOTES
And these top list look like this
1 Novak Djokovic 50
2 Rafael Nadal 35
3 Roger Federer 30
4 Andre Agassi 26
5 Pete Sampras 22
6 Andy Murray 19
7 Chris Evert 13
8 Michael Chang 10
9 Andy Roddick 7
10 Boris Becker 5
11 Björn Borg 1
And I want my top list look like this
// FINALIST // Limit first 4 // green font
1 Novak Djokovic 50
2 Rafael Nadal 35
3 Roger Federer 30
4 Andre Agassi 26
// OTHERS // All other except first 4 and last 2 // black font
5 Pete Sampras 22
6 Andy Murray 19
7 Chris Evert 13
8 Michael Chang 10
9 Andy Roddick 7
// FALL OUT // Limit last 2 // red font
10 Boris Becker 5
11 Björn Borg 1
I hope you understand me and that someone knows how to solve this problem.
Thank you.

You can use this code:
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
$max = mysql_num_rows($upit);
$max = $max - 2;
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
if ($pos < 5){
// first 4 in different color. Green Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} elseif ($pos <= $max) {
//from 5th to 3rd last (left 2 from bottom) in different color. Black Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} else {
// last 2 in different color. Red Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
}

My guess is you're wanting something like this... you can then change your echo code based on how you want to format it.
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
if ($pos < 5){
// finalist format (1-4)
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} elseif ($pos > 9) {
// format fallout users (9+)
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} else {
// format other (5-9)
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
}

Assuming first 4 in different color, from 5th to 3rd last (left 2 from bottom) in different color and last 2 in different color.
So, first find total number of row from SQL query so that we can put 2nd if condition.
$pos=0;
$upit = mysql_query("SELECT * FROM wp_entries ORDER BY vote DESC");
$max = mysql_num_rows($upit);
$max = $max - 2;
while ($sms = mysql_fetch_array($upit)) {
$pos++;
$data = unserialize($sms['data']);
if ($pos < 5){
// first 4 in different color. Green Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} elseif ($pos <= $max) {
//from 5th to 3rd last (left 2 from bottom) in different color. Black Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
} else {
// last 2 in different color. Red Font
echo " ".$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms[vote]." ";
}
}

Assuming you need HTML output, here is a very crude way of doing it:
<?php
$pos = 0;
if( $upit = mysql_query( "SELECT * FROM wp_entries ORDER BY vote DESC" ) )
{
$num_rows = mysql_num_rows( $upit );
if( $num_rows > 0 )
{
echo '<ul>';
while ($sms = mysql_fetch_array($upit))
{
$pos++;
$style = "";
if ($pos < 5)
{
$style = ' style="color:#00FF00;"';
}
elseif ($pos <= ($num_rows-2))
{
$style = ' style="color:#000000;"';
}
else
{
$style = ' style="color:#FF0000;"';
}
$data = unserialize($sms['data']);
echo ' <li'.$style.'>'.$pos." ".$data[1]['value']." ".$data[2]['value']." ".$sms['vote']."<li>";
}
echo '<ul>';
}
}
?>

Related

PHP - create a tournament results order from array

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

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++;
}

How to count the frequency for items in a prepared query?

I have a prepared query with the following result:
12
12
12
14
14
14
14
14
11
11
2
2
2
I simply want to return the number and its frequency:
12 3
14 5
11 2
2 3
My code is as follows:
$count =0;
while($DNB -> fetch())
{
// echo "<br/>";
$nomatch = 0;
if($count ==0)
{
array_push($array, array($postalcode ,1));
// echo $array[0][1];
}
else
{
for($i = 0; $i < count($array);$i++)
{
if($array[$i][0] != $postalcode)
{
$nomatch ++;
if($nomatch == count($array) -1)
{
array_push($array, array($postalcode ,1));
//echo $array[$i][1];
}
}
else
{
$array[$i][1]++;
}
}
}
$count = $count +1;
}
I am not sure what I am doing wrong.
You should use "SELECT id, COUNT (*) FROM table GROUP BY id" as the initial sql query.

Categories