Different value in While loop - php

i want to get only 4 values from while loop in different variables.For example i want like this
$Var1 = "value1";
$Var2 = "value2";
$Var3 = "value3";
$Var4 = "value4";
here is my while loop
while($rw = $oAppl->row($rsimg))
{
//get value here
$var1 = $rw['thumb'];
}
But no value can be repeatable,i only have thumb returned.

If you want to set var1, 2, 3, 4 then stop, you need to keep track how many iterations the loop has gone through. (Alternatively a for loop may perform this task better)
$i = 1;
while ($rw = $oAppl->row($rsimg)) {
if ($i > 4) break;
eval("$Var" . $i . " = '" . $rw['thumb'] . "';");
$i++;
}
If storing values in $varNUM is not a requirement, I would suggest using an array to store these variables instead of using separate variables.

you cannot store more than one value inside a variable, you can either echo while looping
while($rw = $oAppl->row($rsimg))
{
//get value here
echo $rw['thumb'] . '<br>';
}
or create a new array to use all values later
$thumbs = array();
while($rw = $oAppl->row($rsimg))
{
//get value here
$thumbs[] = $rw['thumb'];
}

Related

is it posible to auto increment variable name after a while loop?

I need to create a php file with a hundred variables, which are all identical except for their id.
PHP Code
$var1 = get_input('myvar1');
$var2 = get_input('myvar2');
$var3 = get_input('myvar3');
$var4 = get_input('myvar4');
...
$var30 = get_input('myvar30');
I wonder if it is possible to create only one line as a model, and is replicated 30 times?
I think you are looking after something like this :
$vars = [];
for($i = 1; $i <= 30; $i++) {
$vars[] = get_input('myvar' . $i);
}
this is a job for arrays
$var = array_fill(1, 30, 'myvar');
use the array key as your "id"
Why bother with arrays when you can create the variables like so. The variables names are also set dynamically just like the values.
for ($i = 1; $i <= 100; $i++) {
${'var' . $i} = get_input('myvar' . $i);
}

I need a counter within a counter

I have searched for this, can't find it and it should be simple, but now I'm crosseyed. Forgive me - I've only been at this for a few months.
I need a counter within a counter in php, such that I pair $Id1 with $Id2, then $Id3, then $Id4, etc. for a single loop through, and then for the second loop pair $Id2 with $Id3, then $Id4, then $Id5 etc. I get the Ids from a sql query, then I use both of them to run a calculation of their relationship, but first I just need the structure to run these two loops, one within the other. Thanks for any help and your patience.
Edited to add what I have so far:
$collection = [];
$sql = 'SELECT id, name FROM table';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$collection[] = $row;
}
$ct = count($collection);
for ($i = 0; $i < $ct; $i++)
{
$Id1 = $collection[$i]['id'];
for ($j = 0; $j < $ct; $j++)
{
$Id2 = $collection[$j]['id'];
if($Id1 != $Id2){
echo 'IDs: ' . $Id1 . ' ' . $Id2 . '<br>';
}
}
}
}
If you fetch the IDs from your query into an array like this: $ids = [1,2,3,4,5,6,7,8];, you can get a list of pairs using array_chunk, then shifting off the first element, and repeating this process until the array is empty.
while ($ids) { // repeat until empty
$pairs = array_chunk($ids, 2); // split into pairs
foreach ($pairs as $pair) {
if (count($pair) == 2) { // verify that you have a pair (last element will
// have only one item when count($ids) is odd)
var_dump($pair); // do something with your pair of IDs
}
}
$remove_first = array_shift($ids); // shift off the first ID
}
Please note that using array_shift like this will destroy your input array, so if you need to do something else with it as well, make a copy of it before using this approach.

php sum the values seperated by special character

I need to sum the result set values separated by "|" inside the loop eg. set of values 10|2, 6|2, 8|1 should result in 24|5.
here is my code:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XX","XXX","XXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$Totfiles = 0;
$file_minutes = 0;
$Tot_minutes=0;
$Pending=0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
$response["Details"]['Pending'] = $Pending;
$response["Details"]['Tot_minutes'] = $Tot_minutes;
echo json_encode($response);
?>
$row["Pending"] contains the values which are to be summed
result am getting now,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
my expected result,
"Pending":"33|14"
This is what you are aiming at i think, you make an array first containing 2 values, on each iteration through the loop you add the new values to them and at the end you can implode it into a string again
// Start with an array containing 0 twice
$Totalpending = [0,0];
while(($row = mysqli_fetch_array($query)))
{
// On each loop we add the left value to the first value in the array and the right value to the second value in the array
$tmp = explode("|", $row['Pending']);
$Totalpending[0] += $tmp[0];
$Totalpending[1] += $tmp[1];
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you.
$stringTotalpending = implode('|',$Totalpending);
the string value you want will then be in $stringTotalpending
So Firstly, we need to explode the values from $row["Pending"].
$arr = explode("|", $row["Pending"]);
Now use a loop to add those two numbers:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
Now the $temp would contain the result.
As simple as that.
And also as a side note, your code is vulnerable to SQL-Injection attacks.
What about evaling the same string with '|' replaced by '+' ?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
Note preg_replace() to sanitize input. Can be avoided if input is already sanitized

More elegant way of looping through array and aggregating result in PHP

I need to loop through a set of data (example below) and generate an aggregate. Original data format is CSV (but could be other kind).
LOGON;QUERY;COUNT
L1;Q1;1
L1;Q1;2
L1;Q2;3
L2;Q2;1
I need to group the quantities by LOGON and QUERY, so at the end I would have an array like:
"L1-Q1" => 3,
"L1-Q2" => 3,
"L2-Q1" => 1,
I usually use a code like this:
$logon = NULL;
$query = NULL;
$count = 0;
$result = array();
// just imagine I get each line as a named array
foreach ($csvline as $line) {
if ($logon != $line['logon'] || $query != $line['query']) {
if ($logon !== NULL) {
$result[$logon . $query] = $count;
}
$logon = $line['logon'];
$query = $line['query'];
$count = 0;
}
$count += $line['count'];
}
$result[$logon . $query] = $count;
Sincerely, I don't think this is nice, as I have to repeat last statement to include last line. So, is there a more elegant way of solving this in PHP?
Thanks!
You simply would need to check for the existence of a key, then increment - create missing keys at any time with value 0.
Then you dont need to repeat anything at any time:
$result = array();
foreach ($csvline as $line) {
if (!isset($result[$line['logon'] . $line['query']])){
//create entry
$result[$line['logon'] . $line['query']] = 0;
}
//increment, no matter what we encounter
$result[$line['logon'] . $line['query']] += $line['count'];
}
For readability and to avoid misstakes, you should generate the key just one time, instead of performing the same concatenation over and over:
foreach ($csvline as $line) {
$curKey = $line['logon'] . $line['query'];
if (!isset($result[$curKey])){
//create entry
$result[$curKey] = 0;
}
//increment, no matter what we encounter
$result[$curKey] += $line['count'];
}
this would allow you to refactor the key without touching several lines of code.

How to implode many available to one available using loop for?

How to implode many available to one available using loop for ?
i have many available like
$var_1 = one;
$var_2 = two;
$var_3 = three;
$var_4 = four;
$var_5 = five;
$var_6 = six;
$var_7 = seven;
$var_8 = eight;
$var_9 = nine;
$var_10 = ten;
$var_11 = eleven;
and then i want to implode to one available
$all_data = one,two,three,four,five,six,seven,eight,nine,ten,eleven,
but i want to using loop for like this
for ( $i=1;$i<12;$i++ )
{
$all_data = ${var_$i}.",";
}
how can i do ? thank you for every comment ^^
$all_data = implode(',', array($var_1, $var_2, ..., $var_11));
Any time you find yourself creating a bunch of variables with numeric names like this, say to yourself: "I really should be using an array". There's almost never a good reason for this type of programming.
For the for loop you're trying to write, see the PHP documentation on Variable Variables.
$all_data = '';
for ($i = 1; $i < 12; $i++) {
$all_data .= ${'var_'.$i} . ',';
}

Categories