creating and displaying info from two different arrays? - php

I'm pretty much a PHP beginner, although I can copy and paste like no one's business and generally I'm able to pick it apart and figure out what's going on :) This is my first post here, but I've gotten lots of help from other answers, so thanks for all the past and hopefully future help!
Basically what I'm trying to replicate here is an equestrian show jumping event, in which each knockdown of a pole equals four faults, and time faults are given for going over the time allowed. All horses who jump clear, that is, with zero faults, go on to a jump-off round, where they may or may not incur faults.
My current issue is using for and foreach loops to advance two different arrays. The problem I'm having is that if I get one array working, the other stops. One of the arrays needs to be shuffled, the other needs to be sorted in numerical order. Basically it's a randomizer which will take a series of horses and give them placings and then assign a weight random number of faults (it's for a horse game, nerdy, I know). Here is the code I'm working with:
index.php
<form action="classes.php" method="post">
How many classes do you wish to randomize?<br />
<input type="text" name="number"><br />
<input type="submit" /><br />
</form>
classes.php
<form action="action.php" method="post">
<?php
$number = $_POST['number']; //This is the desired value of Looping
echo '<input type="hidden" value="' . $number . '" name="number">';
$i = 1; //First we set the count to be zero
while ($i<=$number) {
echo '
Class: <input type="text" name="class' . $i . '"><br />
<textarea cols="100" rows="20" name="entries' . $i . '"></textarea><br />
<br />';
$i++; //Increase the value of the count by 1
};
?>
<input type="submit" /><br />
</form>
action.php
$number = $_POST['number']; //This is the desired value of Looping
function array_rand_weighted($values) {
$r = mt_rand(1, array_sum($values));
foreach ($values as $item => $weight) {
if ($r <= $weight) return $item;
$r -= $weight;
}
}
for ($i=1; $i<=$number; $i++) {
$class[$i] = $_POST['class'.$i];
//trim off excess whitespace off the whole
$text[$i] = trim($_POST['entries'.$i]);
//explode all separate lines into an array
$textAr[$i] = explode("\n", $text[$i]);
//trim all lines contained in the array.
$textAr[$i] = array_filter($textAr[$i], 'trim');
//shuffle the results
shuffle($textAr[$i]);
//add faults
//loop through the lines
echo '<div id="output">
[b]' . $class[$i] . '[/b]<br />';
foreach($textAr[$i] as $key[$i]=>$line[$i]){
$knockdowns = array( 0 => 20, 1 => 25, 2 => 30, 3 => 10, 4 => 8, 5 => 7); // knockdowns
$knockdowns = array_rand_weighted($knockdowns)*4;
$timefaults = array( 0 => 75, 1 => 10, 2 => 10, 3 => 5); // time faults
$timefaults = array_rand_weighted($timefaults);
$faultsadded = $knockdowns + $timefaults;
$faults[$i] = $faultsadded;
}
asort($faults);
foreach($textAr[$i] as $key[$i]=>$line[$i]){
echo $key + 1,". " . $line . " (" . $faults[$i] . " Faults)<br />";
}
echo '</div>';
}
At present, this code is producing the randomized results I need, but not the faults. When I am able to get it to produce the full set of faults, the list of random horses stops functioning. I have never been able to get the faults to sort in order of value (0-20+). I found another answer using array_combine, and thought maybe to use this, but I need the key (I think- maybe I don't really?).
If you want to see it in action, here is the link: http://www.eecreates.com/randomizer/dhjc%20randomizer/ it's a multi-class randomizer, so on the first page you put the number of classes you want to randomize, then the next page you input the class name and horses entered.
The final product I'm going for would look something like this:
Show Jumping Class
penny (0 Faults | 0 Faults)
sheldon (0 Faults | 4 Faults)
raj (4 Faults)
leonard (5 Faults)
howard (8 Faults)
amy farrah fowler (8 Faults)
bernadette (9 Faults)
I'd also like for it to show a second set of faults for those horses who have zero to begin with, but of course one thing at a time. :) Thank you!

Totally new answer. index.php remains unchanged. I've reworked the code in classes.php to use named arrays. This simplifies the processing in action.php. See below for notes on that. The code here will need to be wrapped in a suitable HTML page layout.
Note that although the code changes are extensive I have minimised the changes to the data structures. This is not necessarily the way I'd handle the data structures if I was starting from scratch.
classes.php
<form action="action.php" method="post">
<?php
$number = $_POST['number']; //This is the desired value of Looping
echo '<input type="hidden" value="' . $number . '" name="number">';
$i = 1; //First we set the count to be zero
while ($i<=$number) {
echo '
Class: <input type="text" name="class[]"><br />
<textarea cols="100" rows="20" name="entries[]"></textarea><br />
<br />';
$i++; //Increase the value of the count by 1
};
?>
<input type="submit" /><br />
</form>
action.php
I've moved the weighted random faults code into its own function. Since the data coming from classes.php is now already in array form I've simplified the processing, and separated it from the output. Once the processing is done and the number of faults generated, a pair of nested loops generates the output by class and entrant.
<?php
function array_rand_weighted($values) {
$r = mt_rand(1, array_sum($values));
foreach ($values as $item => $weight) {
if ($r <= $weight) return $item;
$r -= $weight;
}
}
// generate a random value for faults and return in sorted order, ascending.
function generateFaults($numEntries) {
$faults = array();
while ($numEntries) {
$knockdowns = array( 0 => 20, 1 => 25, 2 => 30, 3 => 10, 4 => 8, 5 => 7); // knockdowns
$knockdowns = array_rand_weighted($knockdowns)*4;
$timefaults = array( 0 => 75, 1 => 10, 2 => 10, 3 => 5); // time faults
$timefaults = array_rand_weighted($timefaults);
$faults[] = $knockdowns + $timefaults;
$numEntries--;
}
// echo nl2br(print_r($faults, true));
sort($faults);
return $faults;
}
$textAr = array();
$faults = array();
// Iterate over the entries array, extracting the names of our entrants.
foreach ( $_POST['entries'] as $entries) {
//explode all separate lines into an array
$tempEntries = explode("\n", $entries);
//shuffle the results
shuffle($tempEntries);
//trim all lines contained in the array and assign to next entry in $textAr
$textAr[] = array_filter($tempEntries, 'trim');
//add faults
$faults[] = generateFaults(count($tempEntries));
}
//loop through the lines
// echo nl2br(print_r($faults, true));
for ($i=0; $i<count($_POST['class']); $i++) {
echo '<div id="output">
<b>' . $_POST['class'][$i] . '</b><br />';
for($j = 0; $j<count($textAr[$i]); $j++) {
echo $j + 1,". " . $textAr[$i][$j] . " (" . $faults[$i][$j] . " Faults)<br />";
}
echo '</div>';
}
?>
Footnote:

Related

Increment number php every next number

everything good ? I'm having a problem where I'm a beginner in php and would need help.
the user must enter an initial number, for example: 1
<input type="number" name"number" id="number">
where he then informs the quantity: 30
<input type="number" name"qtd" id="qtd">
in case I would like to make a loop in which every 10 repetitions are incremented a new number.
the result of the above example would be:
1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3, 3,3,3,3,3,3
its possible ?
here look my code that i was trying , but i couldn't find a logical way .
<?php
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
//echo $_POST['sequencial'];
for ($i = 1; $i <= 100; $i++){
echo $i. "<br>";
}
?>
You can do it that way. It works very nice.
$str =array();
for($i=0;$i<10;$i++)
{
for($j=0;$j<10;$j++){
$str[]=$i;
}
$j=0;
}
echo implode($str,',');

Division with php

Im trying to get out an average value from a vote function.
<?php
$file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = str_split($textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum = $sum + intval($vote);
}
echo "Average: " . $sum;
?>
Simple by substitute (+) with a (/), and even tried a (%). But still getting error message.
Would appreciate alot if anyone could help me out and tell me what im doing wrong.
/thanks
Edit
Sidenote: Please read an explanation under "First answer given" further down below.
This version will take into account any blank lines in a file, if the content looks like:
1
2
3
// <- blank line
Sidenote: Please provide a sample of your text file. A comment has already been given to that effect.
PHP
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = array_filter(array_map("trim", file("textfile.txt")), "strlen");
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
First answer given
Using the following in a text file: (since no example of file content was given)
5
5
5
IMPORTANT NOTE: There should not be a carriage return after the last entry.
produced
Number of votes: 5
Average: 3
which is false, since there are 3 entries in the text file.
explode() should be used, and not str_split()
The following using the same text file produced:
Number of votes: 3
Average: 5
which is correct. In simple mathematics, averages are done by adding all numbers then dividing them by how many numbers there are.
In this case it's 3 numbers (all 5's) added equals 15, divided by 3 is 5.
Sidenote: The first line is not required $file = file("textfile2.txt");
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = explode("\n", $textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
Footnotes:
If the average comes out to 8.33333 and you would like it to be rounded off to 8, use:
echo "Average: " . floor($avg);
If the average comes out to 8.33333 and would like it to be as 9 you would use:
echo "Average: " . ceil($avg);
ceil() function
floor() function
You may be mixing in stuff that can't be divided, like text, etc. I don't know what your text file looks like. intval may be having a problem with arrays. You may try:
foreach ($textfill as $vote) {
if(is_int($vote) {
$sum += $vote;
}
}
echo "Average: " . $sum;
Lower school math says:
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
The average value is calculated by divide the sum with the number of votes. This line will print the average value:
echo "Average: " . $sum/count($textfill);

Check through an array and identify matching numbers

I am working on a scratch card game where by a user purchases a scratch card from me/my store and can then redeem said card by scratching off numbers and matching 3 pictures to win a prize
Like physical scratch cards I want the prizes to be pre configured so that I know when a prize will be won, but obviously the users dont, this is so I can limit the prizes, so it is not true random, but will be random in terms of who wins the prize..
I know how I will setup the prizes but I need to check each data value in an array to ensure that there is not 3 matching numbers, unless they have actually won..
So far I have this (I will neaten it up and shorten the code down soon)
$numbers = array(
0 => rand(0,9),
1 => rand(0,9),
2 => rand(0,9),
3 => rand(0,9),
4 => rand(0,9),
5 => rand(0,9),
6 => rand(0,9),
7 => rand(0,9),
8 => rand(0,9)
);
Which just randomly generates 9 numbers and
echo "<table>";
$i=0;
for($x=0;$x<3;$x++){
echo "<tr>";
for($y=0;$y<3;$y++){
echo "<td>" . $numbers[$i] . "</td>";
$i++;
}
echo "</tr>";
}
Sorts them into a 3x3 table
I know there is the command in_array() which will sort through the array looking for certain values but I dont want to run an endless loop checking each value to see if I get a match, because it's labor intensive and would be messy as well.
I'm looking for a suggestion anyone might have so I can sort through the array and see if any 3 numbers exist, if they do, and they're not suppost to (ie the user hasn't actually won a prize) then one should be changed to a new number.
So thank you in advance for your help guys I look forward to your suggestions
Luke
**** EDIT **
+More info
To pick the winners I will use a database query such as this
$stock = $conn -> query("SELECT DISTINCT * FROM codes WHERE Available = 1 AND 0 = FLOOR(RAND()*Chance) ORDER BY RAND()");
Each code will have a set chance to win and if it matches up it will be shown, depending on the code won a certain prize will show
$stock = $conn -> query("SELECT DISTINCT * FROM codes WHERE Available = 1 AND Win = 1);
'Win' will be a table in the database which each time someone plays the game it goes down by 1
So each code will have the table Win which when it hits 1 it will pop out the in the next game
These are two ways I can think of doing it which I think will work, both ways roughly allow me to control when and if someone wins but the second solution is obviously a more accurate way of doing it
how about not changing a number if a triple one occurs, but preventing a triple one occurs.
function createScratchRange()
{
$result = array();
$options = array_merge(range(0,9), range(0,9));
for ($i = 0; $i < 9; $i++)
{
$key = array_rand($options, 1);
$result[] = $options[$key];
unset($options[$key]);
}
return $result;
}
and you might want to be able to create winners:
function createWinner()
{
$winningNumber = rand(0,9);
$result = array();
$possibleNumbers = range(0,9);
unset($possibleNumbers[$winningNumber]);
$options = array_merge($possibleNumbers,$possibleNumbers);
for ($i = 0; $i < 9; $i++)
{
$key = array_rand($options, 1);
$result[] = $options[$key];
unset($options[$key]);
}
// looks random now.. but no winning numbers... Lets just stick them in there.
$keys = array_rand($result, 3);
foreach($keys as $key)
{
$result[$key] = $winningNumber;
}
return $result;
}
and for testing:
var_dump(createScratchRange()); // this will never give 3 identical numbers in the array.
var_dump(createWinner()); // this will ALWAYS give 3 identical numbers, but never 2 sets of 3 identical numbers

issue in printing dimension of numbers php

I am just a beginner in PHP. I am trying to write program to print numbers like following.
1 1
12 21
123 321
1234 4321
1234554321
I have written the following code.
<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
echo "<br />";
for($j=1; $j<=$i; $j++)
{
echo $j;
}
}
?>
The result displays the following.
1
12
123
1234
12345
I could not reverse it like
1
21
321
4321
54321
How can I do this?
The simplest, hard coded version:
<?php
$text = "1 1
12 21
123 321
1234 4321
1234554321";
echo $text;
?>
Edit
A more generic solution:
<?php
$n = 5;
$seq1 = '';
$seq2 = '';
$format1 = sprintf("%%-%su", $n); //right justified with spaces
$format2 = sprintf("%%%su", $n); //left justified with spaces
for($i=1; $i<=$n;$i++){
$seq1 .= $i;
$seq2 = strrev($seq1);
echo sprintf("$format1$format2\n", $seq1, $seq2);
};
?>
Okay. What you wrote is pretty good. There need to be several changes in order to do what you wanted though. The first problem is that you are rendering it to HTML - and HTML does not render spaces (which we'll need). Two solutions: you use for space, and make sure you use a proportional font, or you wrap everything into a <pre> tag to achieve pretty much the same thing. So, echo "<pre>"; at the start, echo "</pre>"; at the end.
Next - don't have the inner loop go to $i. Let it go to 5 every time, and print a number if $j <= $i, and a space otherwise.
Then, right next to this loop, do another one, but in reverse (starting with 5 and ending with 1), but doing the very same thing.
Viola is a musical instrument.
Here is my solution to your problem.
It isn't the best solution because it doesn't take into account that you could be using numbers higher than 9, in which case it will push the numbers out of line with each other.
But the point is that it is still the start of a solution that you could work on if needed.
You can use an array to store the numbers you want to print.
Because the numbers are in an array it means we can just use a foreach loop to make sure all of the numbers get printed.
You can use PHP's str_repeat() function to figure out how many spaces you need to put in between each string of numbers.
The below solution will only work if you use an array with the default number indicies as opposed to an associative array.
This is because it uses the $key variable in part of the calculation for the str_repeat() function.
If you would rather not use the $key variable then you should be able to figure out how to change that.
When it come to reversing the numbers they have already been stored in a string so you can just use PHP's strrev() function to take care of that and store them in another variable.
Finally you just have to print a line to the document with a line break at the end.
Note that the str_repeat() function is repeating the HTML entity.
This is because the browser will just compress normal white space down to 1 character.
Also note that I have included a style block to change the font to monospace.
This is to ensure that the numbers all line up with each other.
<style>
html, body {
font: 1em monospace;
}
</style>
<?php
$numbers = array(1, 2, 3, 4, 5);
$numbers_length = count($numbers);
$print_numbers = '';
$print_numbers_rev = '';
foreach($numbers as $key => $value) {
$spaces = str_repeat(' ', ($numbers_length - ($key + 1)) * 2);
$print_numbers .= $value;
$print_numbers_rev = strrev($print_numbers);
echo $print_numbers . $spaces . $print_numbers_rev . '<br />';
}
Edit:
Solution without array:
<style>
html, body {
font: 1em monospace;
}
</style>
<?php
$numbers = 9;
$numbers_length = $numbers + 1;
$print_numbers = '';
$print_numbers_rev = '';
for($i = 0; $i <= $numbers; ++$i) {
$spaces = str_repeat(' ', ($numbers_length - ($i + 1)) * 2);
$print_numbers .= $i;
$print_numbers_rev = strrev($print_numbers);
echo $print_numbers . $spaces . $print_numbers_rev . '<br />';
}
$n = 5;
for ($i = 1; $i <= $n; $i++) {
$counter .= $i;
$spaces = str_repeat(" ", ($n-$i)*2);
echo $counter . $spaces . strrev($counter) . "<br/>";
}
<div style="position:relative;width:100px;height:auto;text-align:right;float:left;">
<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
echo "<br />";
for($j=1; $j<=$i; $j++)
{
echo $j;
}
}
?>
</div>

Constructing HTML to output a set of numbers 5 per line

I am realy stuck with part of my php code! I have a range of numbers from 1 to 40 say that I pull from a table in my database and out put onto the screen using a while loop! with these numbers I am using a submit button which i will replace with a image button later on! Just now i can only get them in one line using a table but I want to get them into groups of say 5 or so colums and then go to next line print the next 5 or so colums! I have been trying for loops but they print out 1111, 2222, 3333, 4444, etc. in diffrent lines which is not what i want! I want,
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc
Please help me i have been baffeld with this for ages this is my code so far!
<?
$q3 = "SELECT * FROM tblgame";
$r3 = mysql_query($q3);
while($row2 = mysql_fetch_array($r3))
{
$game_cost = $row2['game_cost'];
echo "<p>Game ID: ".$row2['game_id'];
echo "<br>Game Day: ".$game_day;
echo "<br>Next Game Date: ".$row2['game_date_day']."/".$row2['game_date_month']."/".$row2['game_date_year'];
$fyear = $row2['game_date_year'];
$fmonth = $row2['game_date_month'];
$fday = $row2['game_date_day'];
$tmonth = $date_month;
$tyear = $date_year;
$tday = $date_day;
$days_between = abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24));
echo "<br>Days till next draw: ". $days_between;
echo "<br />Game Cost: £".$row2['game_cost']."</p>";
?>
<table>
<tr>
<?
$q4 = "SELECT * FROM tblnewgameitem WHERE game_id = $row2[game_id] ORDER BY 'game_number' ";
$r4 = mysql_query($q4);
$n1 = mysql_num_rows($r4);
$i=0;
while($row3 = mysql_fetch_array($r4))
{
?>
<td>
<?
if($row3['user_email'] == "")
{
?>
<form action="buyanumber.php" method="POST">
<input type="hidden" name="game_id" value="<?echo $row2['game_id'];?>">
<input type="hidden" name="num" value="<? echo $row3['game_number']; ?>">
<input type="submit" value="<?echo $row3['game_number'];?>" name="submit">
</form>
<?
}
else
{
$n = $n + 1;
echo " ".$row3['game_number']." ";
}
?>
</td>
<?
}
?>
</tr>
</table>
Please help me i have been stuck on this problem for a good number of days and its driving me loopy lol!
Thank you
Stephen
nested for-loops is the key:
$list=array();
while($row2 = mysql_fetch_array($r3)) $list[] = $row2;
$countList = count($list);
$cols = 5;
$rows = ceil($countList / $maxPerRow);
for ($i=0; $i<$rows; $i++) {
echo 'opening stuff per row... <tr> or something';
for ($j=0; $j<$rows; $j++) {
echo 'your stuff per item... might be somthing like <td>s';
}
echo 'closing stuff per row... </tr> or something';
}
something like this
I'm assuming that the 'real' problem lays somewhere between <table> and </table> and that you want to put the values returned by the fourth query (for some reason mapped to $row3) in a table with 5 columns.
Using the PHP modulo operator ('%'), you could do something like this:
<?php
$r4 = <your mysql_query>
$i = 0;
while ($row3 = mysql_fetch_array($r4)) {
if ($i % 5 == 0) { // true for 0, 5, 10, ...
echo "<tr>";
}
echo "<td>";
// what you want to put between your <td> tags comes here
echo "</td>";
if (($i+1) % 5 == 0) { // true for 4, 9, 14, ...
echo "</tr>";
}
$i++;
}
// if the number of rows is not a multiple of 5, we must clean up after ourselves:
if ($i % 5 != 0) {
echo "<td colspan=\"" + (5-($i % 5)) + "\"> </td></tr>";
}
?>
I haven't tested the code myself.
For the sake of clearity, please consider using proper indentation and consistent variable naming in your code. Also note that using a proper title and less exclamation marks in your question would improve the clearity of it.

Categories