While loop not working with x <=num - php

$x = 1;
$num = 15;
while($x <= $num) {
$res = '[TR][TD="align: left"]'.$x.'[/TD][TD="align: left"][/TD][/TR]';
$x++;
}
echo $res;
That's my code but it only shows the following when I try it:
[TR][TD="align: left"]15[/TD][TD="align: left"][/TD][/TR]
It should show that but instead of only 15 it should be 1-15 inclusive.
Any ideas?

You keep setting $res to a new value rather than appending to it. Using $res .= 'something'; is like saying $res = $res . 'something';. Doing this will allow you to keep the previous value of $res and appending more to the end of it.
$x = 1;
$num = 15;
$res = '';
while($x <= $num) {
$res .= '[TR][TD="align: left"]'.$x.'[/TD][TD="align: left"][/TD][/TR]';
$x++;
}
echo $res;

$x = 1;
$num = 15;
while($x <= $num) {
$res = '[TR][TD="align: left"]'.$x.'[/TD][TD="align: left"][/TD][/TR]';
$x++;
echo $res;
}
Put echo $res; inside the loop, otherwise it will echo just the $res from the last loop cycle instead of all 15 times.

Related

How to read the last result of a while loop using php

i need to put the last while loop result into a variable. How can i return only the last one?
<?php
$x = 0;
$r = rand(0,5);
$d = 10 + $r;
$h = 143;
$counter = 0;
while ($h >= 0) {
echo "The number is: $h <br>";
$h-=$d;
$counter++;
}
?>

PHP: Getting random combinations to specified input

I am trying to display possibilities for additions of specific numbers but have not been getting the right results.
<?php
$num3 = 20;
$set = null;
$balance = $num3;
$dig = mt_rand(1,5);
for($i = $balance; $i > 0; $i -= $dig ){
echo $dig.'<br>';
if($i < 1){
$set .= $i;
$balance = 0;
}
else{
$set .= $dig.'+';
$dig = mt_rand(1,5);
}
}
echo $set.'='.$num3;
?>
Here are some of the outputs:
2+5+1+4+5+3+=20
1+4+3+5+3+=20
3+1+1+2+3+4+4+1+3+=20
Appreciate any pointers. Thank in advance...
Ok, even though the requirement isn't completely clear, here's an approach:
(edit: demonstrating prevention of endless loop)
$max_loops = 1000;
$balance = 20;
$found = [];
while($balance > 0 && $max_loops-- > 0) {
$r = mt_rand(1, 5);
if ($balance - $r >= 0) {
$found[] = $r;
$balance -= $r;
}
}
echo implode(' + ', $found) . ' = '.array_sum($found);
Note: This code has a small risk of getting caught in an endless loop... though it's doubtful that it'll ever happen :)
Edit: Now the loop contains a hard-limit of 1000 iterations, after which the loop will end for sure...
To provoke an endless loop, set $balance = 7 and modify mt_rand(4, 5).
You can use a recursive function for this:
function randomAddends($target, $maxAddend = 5, $sum = 0, $addends = [])
{
// Return the array of addends when the target is reached
if ($target <= $sum) {
return $addends;
}
// generate a new random addend and add it to the array
$randomAddend = mt_rand(1, min($maxAddend, $target - $sum));
$addends[] = $randomAddend;
// make the recursive call with the new sum
return randomAddends($target, $maxAddend, $sum + $randomAddend, $addends);
}

Array outside while doesn't function

Sorry for the beginner question.
I'm searching about an hour, but I can't understand why my $row outside from the second while doesn't function... The name variable run just the $row var doesn't function...
$i = 0;
while($i < 8)
{
$str = "SELECT * FROM `$name[$i]`";
$result = mysql_query($str, $connessione);
$l = mysql_num_rows($result);
while($l > 1)
{
$strs = "SELECT * FROM `$name[$i]` WHERE `Livello` = '$l'";
$results = mysql_query($strs, $connessione);
$row[$i][$l] = mysql_fetch_array($results);
if I put here the echo I can view the mysql variable
echo $row[$i][$l]['var'];
$l--;
}
if I put here echo $row[$i][$l]['var']; he send me the error " Undefined offset"
$i++;
}
Hope you can help me...
In the place where you put:
echo $row[$i][$l]['var'];
$l value is 0 and you set $row values for $l from 1 to mysql_num_rows($result)
if you put there:
echo $row[$i][1]['var'];
it should work fine assuming mysql_num_rows($result) was more than 1 element.
Probably your code should look like this:
$i = 0;
while($i < 8)
{
$str = "SELECT * FROM `$name[$i]`";
$result = mysql_query($str, $connessione);
$l = mysql_num_rows($result);
while($l > 0) // changed 1 to 0
{
$strs = "SELECT * FROM `$name[$i]` WHERE `Livello` = '$l'";
$results = mysql_query($strs, $connessione);
$row[$i][$l] = mysql_fetch_array($results);
if i put here the echo i can view the mysql variable
echo $row[$i][$l]['var'];
$l--;
}
// added extra loop to display array values
$whileIndex = 0;
while (true) {
if (!isset($row[$i][$whileIndex]['var']) {
break;
}
echo $row[$i][$whileIndex]['var']; // should work
++$whileIndex;
}
$i++;
}
When you try to use echo, $i = 8 and $l = 1. These keys doesn´t exists in your array.

randomly choose one data from blocks of query

I have 100000 records in a table. I need to make a query that reads 10 records and after that 10 more records continuously until the end of the table. For each of the 10 rows groups, I need to pick one random row. Is it possible to accomplish that using a MySQL query? I need some idea to do this. Can anybody help me?
I have tried to do a php loop but it doesn't work.
<?php
include_once ("connection.php");
$data = mysql_query("SELECT * FROM trying");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Insted of this:
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
you can use this:
$rand = array();
$step = 10;
for ($min = 0; $min <= 49; $min = $min + $step)
{
$max = $min + $step;
$rand[] = $result[rand($min,$max)];
}
echo json_encode($rand);
Since you're echoing a json encoded array, I'm assuming you're calling this php file through an AJAX request, and you want subsequent requests for each 10 rows.
If this is the case, a solution to your problem could be this:
Define limit and offset as vars in your javascript
Pass limit and offset with the AJAX request
If the result of the AJAX request isn't empty, increment offset by limit (offset = offset + limit) to use in the next request
Receive limit and offset in the PHP file (use $_GET or $_POST, depends on the type of request)
Include limit and offset in the MySQL query ("SELECT * FROM trying LIMIT $offset, $limit")
Calculate a random number from 0 to 9 (rand(0, 9))
Fetch the nth (rand) row from the MySQL result (see solution below)
Your PHP file should look like this:
include_once ("connection.php");
$limit = mysql_real_escape_string($_GET['limit']); // If post use $_POST
$offset = mysql_real_escape_string($_GET['offset']); // If post use $_POST
$data = mysql_query("SELECT * FROM trying LIMIT $offset, $limit");
$rand = rand(0, 9);
$count = 0;
while($row= mysql_fetch_array($data)) {
if($rand == $count++) {
echo json_encode($row);
break;
}
}
Put the SQL statement in a loop and use the counter as a variable in the Limit:
$count = mysql_query("SELECT * FROM trying");
$total = round(mysql_num_rows($count) / 10);
for ($i=0;$i<$total;$i++) {
$data = mysql_query("SELECT * FROM trying LIMIT ".($i * 10).", 10");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Try with the following:
<?php
include_once ("connection.php");
$query = "SELECT * FROM trying";
$count = 0;
while(true)
{
$data = mysql_query($query." LIMIT ".$count.",10");
$random = rand(1,10);
for($i=1;$i<=$random;$i++)
{
$row = mysql_fetch_array($data);
if($row === false)
{
break 2;
}
}
echo json_encode($row);
$count++;
}
?>
Try this :
<?php
set_time_limit(0);
include_once ("connection.php");
$per = 10;
$start = 0;
$total = 0;
$total_query = mysql_query("SELECT COUNT(*) AS total FROM trying");
if(mysql_num_rows($total_query) == 1) {
$row = mysql_fetch_assoc($total_query);
$total = $row['total'];
$offset = ($start * $per);
$results = array();
while($offset <= $total) {
$tmp = array();
$data_query = mysql_query("SELECT * FROM trying LIMIT ".$offset.",".$per);
while ($row = mysql_fetch_array($data_query)) {
array_push($tmp, array(
'no'=> $row['no'],
'source'=> $row['source'],
'destination'=> $row['destination'])
);
}
array_push($results,$tmp[rand(0,9)]);
unset($tmp);
$start++;
$offset = ($start * $per);
}
echo json_encode($results);
} else {
die("No records found.");
}
?>

How to select a random set of rows?

How can I select a random set of rows
The important bits:
I need to specify the number of random rows to select via a variable.
Say for instance the number of rows I want to select is 10, then it HAS TO select 10 DIFFERENT rows. I don't want it to pick out the same row a few times until it has 10.
The code below picks out 1 random row, how can I tailor this to the above spec?
<?php $rows = get_field('repeater_field_name');
$row_count = count($rows);
$i = rand(0, $row_count - 1);
echo $rows[$i]['sub_field_name']; ?>
<?php
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$rand_rows = array();
for ($i = 0; $i < min($row_count, 10); $i++) {
// Find an index we haven't used already (FYI - this will not scale
// well for large $row_count...)
$r = rand(0, $row_count - 1);
while (array_search($r, $rand_rows) !== false) {
$r = rand(0, $row_count - 1);
}
$rand_rows[] = $r;
echo $rows[$r]['sub_field_name'];
}
?>
This is a better implementation:
<?
$rows_i_want = 10;
$rows = get_field('repeater_field_name');
// Pull out 10 random rows
$rand = array_rand($rows, min(count($rows), $rows_i_want));
// Shuffle the array
shuffle($rand);
foreach ($rand as $row) {
echo $rows[$row]['sub_field_name'];
}
?>
Simply loop through the random row process the number of random rows you want to get.
<?php
$rows_to_get=10;
$rows = get_field('repeater_field_name');
$row_count = count($rows);
$x=0
while($x<$rows_to_get){
echo $rows[rand(0, $row_count - 1)]['sub_field_name'];
$x++;
}
?>
You can give this a try
$rows = get_field('repeater_field_name');
var_dump(__myRand($rows, 10));
function __myRand($rows, $total = 1) {
$rowCount = count($rows);
$output = array();
$x = 0;
$i = mt_rand(0, $rowCount - 1);
while ( $x < $total ) {
if (array_key_exists($i, $output)) {
$i = mt_rand(0, $rowCount - 1);
} else {
$output[$i] = $rows[$i]['sub_field_name'];
$x ++;
}
}
return $output ;
}
A simple solution :
$rows = get_field('repeater_field_name');
$limit = 10;
// build new array
$data = array();
foreach ($rows as $r) { $data[] = $r['sub_field_name']; }
shuffle($data);
$data = array_slice($data, 0, min(count($data), $limit));
foreach ($data as $val) {
// do what you want
echo $val;
}

Categories