I have foreach which consist of the list of candidates. I'm trying to compute the percentage inside the foreach then output the result. I don't know the problem, I want the program to compute the first if statement(talent), after going to the next if statement(distance), then continue the computation. The echo will display the overall computation of percentage. Please help. Thanks in advance
$counter = 0;
$status = array();
foreach($candidate as $c){
$queryResult = mysql_query("SELECT * FROM candidates WHERE id = '$c'");
$row = mysql_fetch_assoc($queryResult);
if($talent == "good"){
$status[$counter] = + 0.10;
}else if($talent == "better"){
$status[$counter] = + 0.05;
}
if($distance == "1200m"){
$status[$counter] = + 0.10;
}else if($distance == "1400m"){
$status[$counter] = + 0.05;
}
echo $status[$counter] * 100 . "%<br>";
$counter ++;
}//foreach end
how about changing those =+ with +=, perhaps that is what you want ..? (e.g., $status[$counter] += 0.10;)
and try to initialize this before the foreach loop..
$array = array_fill(0,$number_of_candidates, 0);
Related
I have a list of requested items that are pulled from the database. What I am looking to do is to get the hourly_rate for each item that is selected and add those values together. I am getting the values I need from the database, but now I am looking to add those values.
//Get total hours from other query
$hours = $row['total_hours'];
//Items requested by user
$requestedItems = "1,2,3";
$items = explode(',', $requestedItems);
//Query
$priceQuery = "SELECT hour_rate,
day_rate,
item_id,
rental_status,
hourly_rental
FROM
products
WHERE
rental_status != 1
AND
item_id = :var
";
$itemDisplay = array();
I loop through and get back the values, but now what I want is to add those returned values together...I tried turning them to integers and adding them together but could not seem to do it.
foreach($items as $var){
$itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
foreach($itemDisplay as $key=>$v){
//Edits added
$itemVar += $v['hour_rate'];
if($hours >= 3){
if($v['hourly_rental'] == '1'){
$hours -= 2;
$itemVar += $v['day_rate'] * $hours;
}else{
$itemVar += $v['day_rate'];
}
}else{
if($v['hourly_rental'] == '1'){
$itemVar += $v['day_rate'];
}else{
// This is the line here that is affecting the value of both items.
//If $day_rate = $v['day_rate'] then the items with hourly_rentals == '1'
//have correct values. If I set $day_rate = 0; then the items with
//hourly_rentals != '1' have correct values
//but not both at the same time. Might need to figure out a better comparison.
$day_rate = $v['day_rate'];
print_r($day_rate);
}
}
}
}
$totalPrice = $itemVar + $day_rate + $delivery_cost;
The price selection function just grabs the values from database (code for clarity)
public function priceSelection($conn, $var, $priceQuery){
$stmt = $conn->prepare($priceQuery);
$stmt->bindParam(":var", $var);
$stmt->execute();
$result = $stmt->fetchAll();
if($stmt->rowCount() > 0){
foreach($result as $row){
$array[] = $row;
}
return $array;
}
return false;
}
Beside the option to Summarize the numbers within the SQL query you may do it in PHP as well.
Avoid resetting the value on each loop step and continuously add the value to $itemVar variable:
<?php
foreach($items as $var){
$itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
foreach($itemDisplay as $key=>$v){
//$itemVar = ''; // do not null the sum value
//Items returned that I would like to be added together
$itemVar += $v['hour_rate'];
//$values = intval($itemVar);
}
}
print_r($itemVar); // print final value
EDIT after OP update
I see two issues in the updated OP code.
the data in the variable $day_rate is set directly and only within the nested foreach loop so this variable keeps the very last value that is set each time the else - else condition is met AND it is the only place where the variable is initiated. This could make some troubles in final calculation.
the $itemVar variable is incrementally calculating its total sum in each loop however the $day_rate is not and more over the problem mentioned in first point. You may need to make a sum of that value as well what you can achieve with this: $day_rate = $v['day_rate'];
potential problem might be the comparison of (xxx == '1') as the PHP dynamically works with the variable entity it will take and convert the value of xxx to most probable to an integer and then converts the string of '1' to the integer as well befor the comparison is made. As an example gues how is compared var_dump(true == '1'); true or false, huh?
Note it is going to be XY problem since the whole structure starts not making any sense to me.
Last EDIT
As general purpose tip for understanding what your code is doing I would recommend any kind of debugger where you can see live status of any variable while the script is processing. Debugging in PHP
Or very simple way of debugging that is simple printing the variable content so you can get at least some idea how to data are calculated.
And of course Always debug your scripts with enabled PHP Error Reporting!
// Counters for
$itemsCounter = 0;
$displayCounter = 0;
foreach($items as $var){
$itemDisplay = $userFile->priceSelection($conn, $var, $priceQuery);
foreach($itemDisplay as $key=>$v){
// Debug current variables rows and $v
echo "Row $itemsCounter::$displayCounter; key=$key;". print_r($v, true);
//Edits added
$itemVar += $v['hour_rate'];
if($hours >= 3){ // WHERE do you get the $hours? Sould it be $v['hour_rate']?
if($v['hourly_rental'] == '1'){
$hours -= 2;
$itemVar += $v['day_rate'] * $hours;
}else{
$itemVar += $v['day_rate'];
}
// Debug current variable $itemVar
echo "itemVar=$itemVar;"
}else{
if($v['hourly_rental'] == '1'){
$itemVar += $v['day_rate'];
}else{
$day_rate = $v['day_rate'];
print_r($day_rate);
}
// Debug current variable $itemVar and new $day_rate
echo "itemVar=$itemVar;day_rate=$day_rate;"
}
$displayCounter++; // iterrate the inner counter
}
// iterrate the counter
$itemsCounter++;
// reset the inner counter for next loop
$displayCounter = 0;
// Debug inserts new line
echo PHP_EOL;
}
$totalPrice = $itemVar + $day_rate + $delivery_cost;
Maybe you just get the amount, it will solve your problem?
$sumHourlyRental = "SELECT SUM(hourly_rental) FROM products WHERE rental_status != 1 AND item_id = :var";
So to answer my own question, I needed to actually do the calculations within the function itself. It works as intended now
//Code on schedule.php page
//Find how many requested items there are
$items = explode(',', $requestedItems);
$item_name = array();
foreach ($items as $var){
$item_name[] = $products->priceChange($conn, $var, $hours);
}
$prices = 0;
foreach($item_name as $price){
$prices += $price;
}
$prices += $delivery_cost;
echo '<button type="button" class="btn" style="color:green;font-weight:bold;">$'.$prices.'</button>';
Then in the function, I added up the values.
public function priceChange($conn, $var, $hours){
$query = "SELECT * FROM products WHERE item_id = :id";
$stmt = $conn->prepare($query);
$stmt->bindParam(":id", $var);
$stmt->execute();
$result = $stmt->fetchAll();
if($stmt->rowCount() > 0){
$total = 0;
foreach($result as $row){
$hour_rate = $row['hour_rate'];
$day_rate = $row['day_rate'];
if($hours == '2'){
$total += $hour_rate;
}else{
if($row['hourly_rental'] == '1'){
$hours -= 2;
$total += $hour_rate + $day_rate * $hours;
}
else{
$total = $hour_rate + $day_rate;
}
}
}
return $total;
}
return false;
}
This code is working fine when the array length is 8 or 10 only. When we are checking this same code for more than 10 array length.it get loading not showing the results.
How do reduce my code. If you have algorithm please share. Please help me.
This program working flow:
$allowed_per_room_accommodation =[2,3,6,5,3,5,2,5,4];
$allowed_per_room_price =[10,30,60,40,30,50,20,60,80];
$search_accommodation = 10;
i am get subsets = [5,5],[5,3,2],[6,4],[6,2,2],[5,2,3],[3,2,5]
Show lowest price room and then equal of 10 accommodation; output like as [5,3,2];
<?php
$dp=array(array());
$GLOBALS['final']=[];
$GLOBALS['room_key']=[];
function display($v,$room_key)
{
$GLOBALS['final'][] = $v;
$GLOBALS['room_key'][] = $room_key;
}
function printSubsetsRec($arr, $i, $sum, $p,$dp,$room_key='')
{
// If we reached end and sum is non-zero. We print
// p[] only if arr[0] is equal to sun OR dp[0][sum]
// is true.
if ($i == 0 && $sum != 0 && $dp[0][$sum]) {
array_push($p,$arr[$i]);
array_push($room_key,$i);
display($p,$room_key);
return $p;
}
// If $sum becomes 0
if ($i == 0 && $sum == 0) {
display($p,$room_key);
return $p;
}
// If given sum can be achieved after ignoring
// current element.
if (isset($dp[$i-1][$sum])) {
// Create a new vector to store path
// if(!is_array(#$b))
// $b = array();
$b = $p;
printSubsetsRec($arr, $i-1, $sum, $b,$dp,$room_key);
}
// If given $sum can be achieved after considering
// current element.
if ($sum >= $arr[$i] && isset($dp[$i-1][$sum-$arr[$i]]))
{
if(!is_array($p))
$p = array();
if(!is_array($room_key))
$room_key = array();
array_push($p,$arr[$i]);
array_push($room_key,$i);
printSubsetsRec($arr, $i-1, $sum-$arr[$i], $p,$dp,$room_key);
}
}
// Prints all subsets of arr[0..n-1] with sum 0.
function printAllSubsets($arr, $n, $sum,$get=[])
{
if ($n == 0 || $sum < 0)
return;
// Sum 0 can always be achieved with 0 elements
// $dp = new bool*[$n];
$dp = array();
for ($i=0; $i<$n; ++$i)
{
// $dp[$i][$sum + 1]=true;
$dp[$i][0] = true;
}
// Sum arr[0] can be achieved with single element
if ($arr[0] <= $sum)
$dp[0][$arr[0]] = true;
// Fill rest of the entries in dp[][]
for ($i = 1; $i < $n; ++$i) {
for ($j = 0; $j < $sum + 1; ++$j) {
// echo $i.'d'.$j.'.ds';
$dp[$i][$j] = ($arr[$i] <= $j) ? (isset($dp[$i-1][$j])?$dp[$i-1][$j]:false) | (isset($dp[$i-1][$j-$arr[$i]])?($dp[$i-1][$j-$arr[$i]]):false) : (isset($dp[$i - 1][$j])?($dp[$i - 1][$j]):false);
}
}
if (isset($dp[$n-1][$sum]) == false) {
return "There are no subsets with";
}
$p;
printSubsetsRec($arr, $n-1, $sum, $p='',$dp);
}
$blockSize = array('2','3','6','5','3','5','2','5','4');
$blockvalue = array('10','30','60','40','30','50','20','60','80');
$blockname = array("map","compass","water","sandwich","glucose","tin","banana","apple","cheese");
$processSize = 10;
$m = count($blockSize);
$n = count($processSize);
// sum of sets in array
printAllSubsets($blockSize, $m, $processSize);
$final_subset_room = '';
$final_set_room_keys = '';
$final_set_room =[];
if($GLOBALS['room_key']){
foreach ($GLOBALS['room_key'] as $set_rooms_key => $set_rooms) {
$tot = 0;
foreach ($set_rooms as $set_rooms) {
$tot += $blockvalue[$set_rooms];
}
$final_set_room[$set_rooms_key] = $tot;
}
asort($final_set_room);
$final_set_room_first_key = key($final_set_room);
$final_all_room['set_room_keys'] = $GLOBALS['room_key'][$final_set_room_first_key];
$final_all_room_price['set_room_price'] = $final_set_room[$final_set_room_first_key];
}
if(isset($final_all_room_price)){
asort($final_all_room_price);
$final_all_room_first_key = key($final_all_room_price);
foreach ($final_all_room['set_room_keys'] as $key_room) {
echo $blockname[$key_room].'---'. $blockvalue[$key_room];
echo '<br>';
}
}
else
echo 'No Results';
?>
I'm assuming your task is, given a list rooms, each with the amount of people it can accommodate and the price, to accommodate 10 people (or any other quantity).
This problem is similar to 0-1 knapsack problem which is solvable in polynomial time. In knapsack problem one aims to maximize the price, here we aim to minimize it. Another thing that is different from classic knapsack problem is that full room cost is charged even if the room is not completely occupied. It may reduce the effectiveness of the algorithm proposed at Wikipedia. Anyway, the implementation isn't going to be straightforward if you have never worked with dynamic programming before.
If you want to know more, CLRS book on algorithms discusses dynamic programming in Chapter 15, and knapsack problem in Chapter 16. In the latter chapter they also prove that 0-1 knapsack problem doesn't have trivial greedy solution.
I have a problem and that is I want to create a link on a website like people can click the link to show certain products only depending on percentage. like for example, i have a column in my database with discount percentage and it will show min discount and max discount. assuming we have min and max discount. $min=12 and $max=94; and I want to put them in links to show only products with certain discounts only like filtering. below is the example of the link.
<a href="#">12% to 20%</a
21% to 30%
31% to 40% and so on until it reaches
81% to 90% and the last will be
91% to 94%
smallest and largest numbers will be coming from a column from database and they can change frequently. i came up with solution and its working fine but my code is too long and its like I took to many steps which could be done in few lines of code. I have pasted my working code below but I am sure this can be reduced to few lines of code.
$catsql25 = "SELECT MAX(down_percentage) as largest FROM hot_deals";
$catquery25 = mysqli_query($conn, $catsql25);
while ($row25 = mysqli_fetch_array($catquery25, MYSQLI_ASSOC)){
$largest_number = $row25['largest'];
}
$catsql26 = "SELECT MIN(down_percentage) as smallest FROM hot_deals";
$catquery26 = mysqli_query($conn, $catsql26);
while ($row26 = mysqli_fetch_array($catquery26, MYSQLI_ASSOC)){
$smallest_number = $row26['smallest'];
}
$array_tens = array(10,20,30,40,50,60,70,80,90,100);
foreach ($array_tens as $value){
if(($value - $smallest_number <= 10) && ($value - $smallest_number > 0)){
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++){
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
}
foreach ($array_tens as $value2){
if(($largest_number - $value2 < 10) && ($largest_number - $value2 > 0)){
$lsst = $value2 + 1;
if($lsst != $largest_number){
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
}
elseif($lsst == $largest_number){
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
I know its all mess but..
Thanks.
First thing you could do is only one SQL Query :
$catsql = "SELECT MAX(down_percentage) as largest, MIN(down_percentage) as smallest FROM hot_deals";
And then you'll need only one loop :
$catquery = mysqli_query($conn, $catsql);
while ($row = mysqli_fetch_array($catquery, MYSQLI_ASSOC)){
$largest_number = $row['largest'];
$smallest_number = $row['smalest'];
}
After that, you could make only one foreach loop. The two "if" conditions could be in the same loop :
foreach ($array_tens as $value) {
if (($value - $smallest_number <= 10) && ($value - $smallest_number > 0)) {
echo '<a href="/exp.php?fst='.$smallest_number.'&lst='.$value.'"><div class="lfmen2">';
echo $smallest_number." to ".$value."</div></a>";
$next_num = $value + 1;
$next_ten = 9;
$stop_num = floor($largest_number / 10);
$stop_num2 = $stop_num * 10;
//echo $stop_num2.'<br>';
$num_rounds = $stop_num2 - $value;
$num_rounds2 = $num_rounds / 10;
//echo $num_rounds2;
for ($i = 1; $i <= $num_rounds2; $i++) {
$end_num = $next_num + $next_ten;
echo '<a href="/exp.php?fst='.$next_num.'&lst='.$end_num.'"><div class="lfmen2">';
echo $next_num;
echo " to ";
echo $end_num;
echo "</div></a>";
$next_num += 10;
$end_num += 10;
}
}
if (($largest_number - $value < 10) && ($largest_number - $value > 0)) {
$lsst = $value + 1;
if ($lsst != $largest_number) {
echo '<div class="lfmen2">'.$lsst." to ".$largest_number."</div>";
} elseif ($lsst == $largest_number) {
echo '<div class="lfmen2">'.$largest_number.'</div>';
}
}
}
To make it more readable, you could also comment your code to know what do what.
This and a good indentation and you're right.
Hope it helps.
I am looping a foreach and i need to make some logic like this:
if the iteration is not the last. Gather up the prices. when the iteration is the last. subtract from the total with the gathered up prices. except the last iteration price. I got the following code not. but it's not working.
$i = 0;
$credit = '';
$count = count($reslist);
foreach ($reslist as $single_reservation) {
//All of the transactions to be settled by course
//$credit = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
if ($i > $count && $single_reservation != end($reslist)) {
$gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
$credit = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
}
//Last iteration need to subtract gathered up sum with total.
else {
$credit = $suminczk - $gather_sum_in_czk;
}
$i++;
}
EDIT: TRYING TO GATHER UP PRICES FOR ALL INTERACTIONS EXECPT LAST:
if ($i != $count - 1 || $i !== $count - 1) {
$gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
$credit = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
}
else {
$credit = $suminczk - $gather_sum_in_czk;
}
The SPL CachingIterator is always one element behind its inner iterator. It can therefore report whether it will produce a next element via ->hasNext().
For the example I'm choosing a generator to demonstrate that this approach doesn't rely on any additional data like e.g. count($array).
<?php
// see http://docs.php.net/CachingIterator
//$cacheit = new CachingIterator( new ArrayIterator( range(1,10) ) );
$cacheit = new CachingIterator( gen_data() );
$sum = 0;
foreach($cacheit as $v) {
if($cacheit->hasNext()) {
$sum+= $v;
}
else {
// ...and another operation for the last iteration
$sum-=$v;
}
}
echo $sum; // 1+2+3+4+5+6+7+8+9-10 = 35
// see http://docs.php.net/generators
function gen_data() {
foreach( range(1,10) as $v ) {
yield $v;
}
}
foreach-ing an array in PHP returns both the key (integer index if pure array) and value. To be able to use the value, use the following construct:
foreach ($array as $key => $value) {
...
}
then you can check whether $key >= count($array) - 1 (remember in a 0-based array, the last element is count($array) - 1.
Your original code almost works, just wrong in the if condition. Use $i >= $count - 1 instead of $i > $count.
So the goal is to be able to create a dynamic value for my progress bar based on dynamic variables from the database. Below is a pseudo code for what i am looking for if its possible:
//League rank names
['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I'];
Lets say i start at bronze_IV to bronze_II i need to calculate that to 100?
and then i need to store that value is that possible to be dynamic?
are you trying something like this,
$data = ['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I'];
$start = $end = 0;
while($element = current($data)) {
if ($element == 'bronze_IV') $start = key($data);
if ($element == 'bronze_I') $end = key($data);
next($data);
}
$percentage = ( (($end-$start) + 1) / count($data) ) * 100;
var_dump($percentage); //float(80)
example with multiple tiers,
#note : badge count for each tier has to be 5 for this to work,
#if you change the count change change the value inside the loop
$data = array(
['silver_V','silver_IV','silver_III','silver_II','silver_I'],
['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I']
);
$start = $end = 0;
$start_badge = 'silver_V';
$end_badge = 'bronze_II';
//loop through tiers
foreach ($data as $key => $tier) {
//loop through badges
while($badge = current($tier)){
//position of the start badge
if ($badge == $start_badge) $start = ($key * 5) + key($tier)+1; //see note
//position of the end badge
if ($badge == $end_badge) $end = ($key * 5) + key($tier)+1; //see note
next($tier);
}
}
//count badges
$badges_count = (count($data, COUNT_RECURSIVE) - count($data));
//calculate percentage
$percentage = ( (($end-$start) + 1) / $badges_count ) * 100;
var_dump($percentage); //float(90)