I have a few problems with my code. I can't get the variable status value outside the For statement. I tried to echo it and it's doing nothing.
Here is my code:
public function handlequiz()
{
$datetime = Date("Y-m-d, h:m:s");
$parameter = DB::table('parameter')->first();
$countchoice = $parameter->multiplechoice;
$customer_answer = new CustomerAnswer;
for ($i=0; $i <= $countchoice; $i++)
{
$radio = Input::get('radio'.$i);
$status = DB::table('quiz_answers')->where('answerid', '=', $radio)->lists('status');
}
$answerimplode = implode(";", $status);
$customer_answer->email = Input::get('email');
$customer_answer->cust_id = Input::get('id');
$customer_answer->multiplechoice = $answerimplode;
$customer_answer->save();
return Redirect::to('quiz')->with('message', FlashMessage::DisplayAlert('Your answer has been submitted.', 'info'));
}
I tried to vardump $status inside for it return me an array so I implode it. But outside for{} it returns nothing.
Is there any suggestion to fix this?
Your for loop is overwriting the $status variable every iteration. Therefore, if the last iteration doesn't find a status value, your $status variable will be an empty array, which when imploded, gives you an empty string.
I'm assuming that quiz_answers.answerid is supposed to be unique, and you're trying to get the one status for each of the radio selections. If your quiz_answers query should only be returning one record per answerid, you're probably looking for the pluck() method, not the lists() method.
$status = array();
for ($i=0; $i <= $countchoice; $i++)
{
$radio = Input::get('radio'.$i);
// add the 'status' value to the $status array
// pluck gets the value of the field from the first result, whereas
// lists would return an array with the value from all the results
$status[] = DB::table('quiz_answers')->where('answerid', '=', $radio)->pluck('status');
}
// use array_filter to remove any empty values in the $status array
$answerimplode = implode(";", array_filter($status));
As optimization, use whereIn function
radios = array();
for ($i=0; $i <= $countchoice; $i++)
$radios[] = Input::get('radio'.$i);
$status = DB::table('quiz_answers')->whereIn('answerid',$radios)->lists('status');
$answerimplode = implode(";", $status);
Related
I am attempting to create a function which will tell me what free numbers are available to use, I have a function which returns the numbers which have already been taken in an array.
I wish to check the returned array with existing elements against a blank array, and if the number is not in the array then push/add it to the empty array to allow me to return an array of available numbers/tickets.
I have tried some examples on here and looked upon PHP documentation on some items trying array_intersect, in_array etc.
I believe the best way to add the free numbers to the empty array is using array_push which has not been implemented into the example code as of yet.
Available numbers function so far:
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
for($i = 1; $i<$maxTickets; $i++){
$x = $i-1;
foreach($takenNumbers as $v){
if(in_array($v, $freeNumbers)){
echo "Element is in array";
break;
} else {
echo $v . "is taken";
}
}
}
//return $freeNumbers;
}
Taken numbers function
function takenNumbers($drawID){
$connect = new mysqli("localhost", "root", "", "dream");
$stmt = $connect->prepare("SELECT * FROM transaction WHERE DrawID = ?");
$stmt->bind_param("i", $drawID);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 0) exit("No rows");
$tickets = array();
while($row = $result->fetch_assoc()){
$id = $row['ID'];
$tickets[] = $row['TicketNumber'];
}
return $tickets;
}
Max tickets is just counting from a database transaction table to count already assigned numbers.
In this current iteration of the project, I am receiving the following "1 is taken" for each loop.
Thanks in advance, I have attempted to explain what I am attempting to do in best terms possible. But if I haven't been able to describe something please reply so I can explain it further.
Instead of checking on each array item, you could get the the difference values between all of the ticket numbers and the taken ticket numbers array using array_diff() :
function freeNumbers($drawID){
$minTickets = 1;
$maxTickets = totalTickets($drawID);
$takenNumbers = takenNumbers($drawID);
$freeNumbers = array();
$allTickets = range(1, $maxTickets);
$freeNumbers = array_values(array_diff($allTickets, $takenNumbers));
//return $freeNumbers;
}
Edit : added array_values() to reset the array index returned from the array_diff() function.
Edit : Or if you prefer to use the array_push() function, you could do it like :
for($i = 1; $i<$maxTickets; $i++){
if(!in_array($i, $takenNumbers)){
array_push($freeNumbers, $i);
}
}
I have three variables retrieved from a database and I would like the first variable to be the key for the second variable and for that second variable to be the key for the third variable. In essence a two-dimensional array.
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$unit_id = $row['id'];
$unit_code = $row['unit_name'];
$unit_description = $row['unit_description'];
$units = [$unit_id => $unit_code];
$units += [$unit_code => $unit_description];
}
return $units;
You can simply make like this
<?php
$unit_id = 'id';
$unit_code = 'unit_name';
$unit_description = 'unit_description';
$units[$unit_id] = [$unit_code=>$unit_description];
//$units[$unit_id][$unit_code] = $unit_description;
print_r($units);
?>
Live demo : https://eval.in/880865
Yess you can do this.
$array = [
'data' => 'my data'
];
now you can do this simply
$array['anotherArray'] = $anotherArray;
If "id", "unit_name" and "unit_description" are respectively the first, second and third value of the database, this is the code:
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$units[$row['id']][$row['unit_name']] = $row['unit_description'];
}
return $units;
If array consists of key, value parts (associative arrays), which your case is like that, you just need to:
$data[$key] = $value;
So in your case it would be:
$units[$unit_code] = $unit_description;
If your arrays' keys are indexed, then using array_push can do the job too:
array_push($units, $unit_description);
I have multiple dates to calculate on database. They are fetched and stored in an array.
How can I have variables for each of the returned values, since I don't know how many of the dates are returned?
Here is what I tried so far:
$get_status = $truckerController->status($gid);
$active_days = 0;
$active_d = array();
foreach ($get_status as $trucker) {
$active_d[] = $trucker->date;
}
list($date1, $date2) = $active_d;
So what I want is to have more than two or three parameters inside list() based on the array value size. Please help me out or suggest other ways to handle this issue.
Not sure if the whole approach is correct, but you can try with something like this.
$get_status = $truckerController->status($gid);
$active_days = 0;
$active_d = array();
$i = 0;
foreach ($get_status as $trucker) {
$i++;
$active_d["date".$i] = $trucker->date;
}
extract($active_d);
http://php.net/manual/en/function.extract.php
Hi I'm am sure this is a silly mistake but I have been staring at this the past 20mins to
no avail. I have an array balance[] that is populated with two values for balance[0]
and balance[1]. These are populated within the first for loop however when I go to use these values outside after this the array balance[0] is empty.
Below is my code and output:
for ($i=0; $i<$counter; $i++){
$x = mysql_query("
SELECT `outputValue` FROM `output` WHERE `outputType`= 'balance' && `period`= '6' && teamID = '$ID[$i]'
")or die($x."<br/><br/>".mysql_error());
// set ID's = to a variable and now get Outputs for each variable(teamID)
$balance = array();
$row = mysql_fetch_assoc($x);
echo $i." = I<br/>";
$balance[$i] = $row['outputValue'];
echo "Team ".$i."Balance = ".$balance[$i]."<br/>";
}
for ($i=0; $i<$counter; $i++){
echo "Team ".$i."Balance = ".$balance[$i]."<br/>";
}
You're initializing the $balance inside of the loop. On each for loop iteration, the $balance value is rewritten with an empty array().
On the first iteration, the $balance is set to an empty array, and then the $balance[0] is set.
On the second iteration, the $balance is set to an empty array again, and then the $balance[1] is set.
So, after the loop, the $balance will only contain one element at the index of $counter-1.
Move the line
$balance = array();
outside of the loop.
I'm new in php and got stuck doing a loop.
I have the following:
an array containing 0 or not named $receivers.
another array containing total of receivers which is a number, named $totalreceivers.
a function querying a table with the id, returning 0 or number, named status().
I want to loop through each status() of the receivers and show the sum at the end. I couldn't get it.
Any help will be appreciated. Thanks in advance.
Here is what I tried:
for ($i = 0; $i < $totalreceivers; $i++)
{
$status = status($receivers[$i]);
foreach ($totalreceivers as $value)
$status = status($receivers[$i]);
echo "the sum of receiver having status different than 0 is";
echo count($status);
}
function status($id)
{
global $dbhost;
global $dbuser;
global $dbpass;
global $dbname;
global $d1;
$q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL", $d1);
while($row2 = mysql_fetch_array($q2))
$rowservice = $row2['value'];
return $rowservice;
}
A couple things in your code don't really make sense. First, you're trying to iterate through $totalreceivers twice, one loop being nested in the other. I doubt that's what you want so you should get rid of one of them. And your first loop has a bad expression: to iterate through $totalreceivers in your first for loop, you need to have your testing expression go against the number of elements in the array and not the array itself (can use count()): for ($i = 0; $i < count($totalreceivers); $i++).
Second, you're resetting the value of $status each time you call status() in your loop. To add to it, use the += operator: $status += status($receivers[$i]);
Third, you're doing the same in status() function with $rowservice; resetting it each iteration of that while loop. Either set it once, or sum it up.
You can simplify this task by letting MySQL do more of the work for you.
You have an array $receivers which presumably contains id's for subscribers to (receivers of) something. (I may use receiver and subscriber interchangeably.)
The status() function retrieves from the database the value for each receiver where the subscription_end_date is null. I am going to assume that there is only one row per subscriber because you only return the last result via the variable $rowservice.
It's unclear from your code if you want a count of receivers with a value other than 0, or if you want a sum of all non-zero values. The question then is:
Do you want to know how many subscribers have nonzero values? or,
Do you want to know the sum of all values for subscribers with nonzero values?
Fortunately both of these can be easily found:
How many receivers have non-zero values?
$allreceivers = implode(',', $receivers);
$query = "SELECT COUNT(id) AS total_receivers
FROM user
WHERE subscription_end_date IS NULL
AND value != 0
AND id IN ($allreceivers);";
$result = mysql_query($query, $d1);
$row = mysql_fetch_array($result);
$total_receivers = $row['total_receivers'];
echo "The number of receivers having status (value) other than 0 is $total_receivers";
What is the sum of all receiver values?
$allreceivers = implode(',', $receivers);
$query = "SELECT SUM(value) AS receiver_value_sum
FROM user
WHERE subscription_end_date IS NULL
AND id IN ($allreceivers);";
$result = mysql_query($query, $d1);
$row = mysql_fetch_array($result);
$receiver_value_sum = $row['receiver_value_sum'];
echo "The sum of receiver values is $receiver_value_sum";
At first glance, it looks like you are just overwriting "$status" on each iteration. Before the loop starts, set $status to an empty array and then add to it on each iteration. For example:
$status = array();
foreach ( $totalreceivers as $value)
{
$status[] = status($receivers[$i]);
}
echo count($status);
I will try to outline some possible problems with your code below:
for ($i = 0; $i < $totalreceivers; $i++) { //This open bracket has no end bracket
/*I assume total receivers is the number of receivers; if that is the case, it shouldn't be an array, but merely a value.*/
$status = status($receivers[$i]);
/*I think you should define the status function before you call it; also, if you are just calling the status function for each value of $receivers, why don't you just do a foreach($receivers as $value) loop, like you did below with $totalreceivers. */
foreach ( $totalreceivers as $value)
/*I'm not sure what $totalreceivers is. You said its an array containing total number of receivers; again, I would think this would be a single value, and not an array*/
{
$status = status($receivers[$i]);
/*looks like you're calling the status function again*/
}
echo "the sum of receiver having status different thant 0 is"; echo count($status);
/* $status at this point would count the value from row2 for the last value in $receivers, and not a count of array values. Perhaps you could do $status[] = status($receivers[$i]), and then count($status) to save each value to an array, then count the elements. */
function status($id){
global $dbhost;
global $dbuser;
global $dbpass;
global $dbname;
/* The values above aren't used in the function; you may want to connect to the database outside of the function, before the foreach loop. */
global $d1 ;
$q2 = mysql_query("select * from user where id ='$id' AND subscription_end_date IS NULL",$d1);
while($row2 = mysql_fetch_array($q2)){
$rowservice = $row2['value'];
}
return $rowservice;
}
/*the rest looks good*/