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++;
}
Related
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
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;
}
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:
basically what I want is display a count until it reaches a certain number, so if I had the number "5" on the screen it would show "1 2 3 4 5". Or if I had the number "3" it would show "1 2 3".
The reason is because im creating a paging system for my MySQL results. The code I have so far is
$result1 = mysql_query("SELECT * FROM questions WHERE subcat = '$conditions'");
$num_rows = mysql_num_rows($result1);
$results_per_page = "3";
$num_pages = $num_rows / $results_per_page;
So it counts how many results there are, for example we will say 12 results. It then devides this number by how many results I want shown per page. In this example its "3". So the answer is "4".
So I now want to have "1 2 3 4" displayed on the screen, however I want each number to be a link.
How do I do this?
Thanks
Ben
foreach( range( 1, $num_pages) as $i) {
echo '' . $i . '';
}
Or, an approach suggested by knittl:
echo implode( ' | ', array_map( function( $i) {
return sprintf( '%d', $i, $i);
}, range( 1, $num_pages)));
Prints something like this:
1 | 2 | 3 | 4 | 5
Use a for loop.
for($i = 1; $i <= $num_pages; $i++){
echo ''.$i.' ';
}
Use a loop:
for($i = 0; $i < $num_pages; ++$i) {
printf('page %d', $i, $i);
}
I need to create 3 HTML columns in PHP with data returned from MySQL. I would like the data split evenly between all 3 columns... How would I go about doing this?
You could try doing something like this:
$result = mysql_query("SELECT value FROM table");
$i = 0;
echo '<table><tr>';
while ($row = mysql_fetch_row($result)){
echo '<td>' . $row[0] . '</td>';
if ($i++ == 2) echo '</tr><tr>'
}
echo '</tr></table>';
note this table has the values ordered like
1 2 3
4 5 6
7 8 9
If you wanted it vertically like
1 4 7
2 5 8
3 6 9
Then you should do something like
$result = mysql_query("SELECT value FROM table");
$data = Array();
while ($row = mysql_fetch_row($result)) $data[] = $row;
for ($i = 0; $i < count($data) / 3; $i++){
echo '<table><tr>';
for ($j = 0; $j < 3; $j++){
echo '<td>' . $data[ $i + $j * 3] . '</td>';
}
echo '</tr><tr>'
}
echo '</tr></table>';
You can create an HTML table and then use a PHP foreach loop to loop through the MySQL result set and put each field in its own table. At the end of each record returned by the MySQL query, end the table row and start a new one.
A small detail, if return more entries than the "fetch_row" use "break", based on the answer from #Robbie: Spliting mysql data in 3 columns error -3-columns-error