PHP - Discount Math On An Array
Having to go into somebody else's code yet again! Gah! Originally the totaling page just subtracted a flat discount. But now the client wants to be able to subtract percentage discounts and 'per item' discounts. In the discount table I added a field to determine whether the discount chosen is to be applied as flat off total, flat per item, % off total, and % off each item. I also entered a field that can have a class id, in case this discount is only for that class. (the intention being that otherwise the discount is on anything)
I've got a session variable that generates something like : Array ( [217] => 1 [215] => 2 ) meaning 1 person in class #217, and 2 people in class 215. $_SESSION['s_to_be_added'] = array_filter($_POST['participantqty']); Then on the page I'm concerned with, I've been trying to write the script. I know I still need some math stuff figured out But how do I take the array, do the math, and then generate an overall cost for the whole thing? and this is just the discounting? I don't even have a clue how to work in delimiting it if there's a class id.. did any of that make sense? Code: [Select] <?php // the above is the array I want to use to $passed_array = array_filter($_SESSION['s_to_be_added']); // this is the discount 'code' the user entered. $discount = mysql_escape_string($_POST['discount']); // just a donation added after everything. $donation = mysql_escape_string($_POST['donation']); // finding the discount that matches the discount 'code' entered. $query_selectAllItems_events = "SELECT discount_amount,discount_type,workshop_link_1 FROM tbl_discount where discount_value = '$discount'"; $result_all_events = mysql_query($query_selectAllItems_events); $numRows_all_events = mysql_num_rows($result_all_events); $num=mysql_num_rows($result_all_events); $z_row = mysql_fetch_array($result_all_events); // this is just a number: 1, 20, 90 etc. $discount_amount = $z_row['discount_amount']; /*this is 1,2,3,4 - for each type of discount 1- flat 2- flat per item 3- discount on all, 4- discount per item */ $discount_type = $z_row['discount_type']; // the workshop id if the discount is onlyh for this workshop $discount_link_1 = $z_row['workshop_link_1']; // just a description $discount_name = $z_row['discount_name']; if ($discount_type ==1) { /* flat discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==2)) { /* discount per item total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total - $discount_amount); $final_total = ($final_total + $donation); } elseif ($discount_type ==3)) { /* percentage discount on total here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } elseif ($discount_type ==4)) { /* percentage discount per item here */ $total = mysql_escape_string($_POST['total']); $final_total = ($total * ($discount_amount/100)); $final_total = ($final_total + $donation); } ?> Similar TutorialsI have to take over somebody else's project. So I have the combination of being a beginner, not understanding their code well, and not experienced with arrays. I'm in over my head. I have an array passed to the page, that would be something like this: Array ( [215] => [213] => 1 [212] => 2 [214] => ) the user chose 1 person in 213, and 2 people in 212 and I basically need to break it apart to do math like this: (#people x cost of 213 = totalcostA ) + (# people x cost of 212 = totalcostB) = total The broken down data goes into the database, and the total is used for the cart. I've taken suggestions and gotten to this jumbled mess: Code: [Select] $ids = $_POST['workshop_id']; print_r($_POST['participantqty']); // the above shows the arrays are sending to this page and printing correctly: Array ( [215] => [213] => 1 [212] => 2 [214] => ) foreach ($_POST['workshop_id'] as $id){ $qty = $_POST['participatqty'][$id]; } if(sizeof($_POST['workshop_id'])) { // loop through array $number = count($ids); for ($i=0; $i<=$number; $i++) { // store a single item number and description in local variables $itno = $ids[$i]; $qty_insert = $qty[$i]; $query_insertItemWorkshop = "INSERT INTO tbl_registration_workshop (registration_id, workshop_id, regworkshop_qty) VALUES ('$reg_id', '$itno', '$qty_insert')"; $dberror = ""; $ret = mysql_query($query_insertItemWorkshop); $query_selectAllItems_events = 'SELECT * FROM tbl_workshops where workshop_id = '.$itno; @$result_all_events = mysql_query($query_selectAllItems_events); @$numRows_all_events = mysql_num_rows($result_all_events); @$num=mysql_num_rows($result_all_events); @$z_row = mysql_fetch_array($result_all_events); // I want the below to work, but it won't until I can figure out how to break it all down. $qty_total=$qty_insert*$z_row['workshop_price']; $total = $total + $qty_total; if ($ids[$i] <> '') { // I want the info to also appear below, but can't until I figure out how to break them down. echo $total_students; echo "<tr><td valign=top><b>Description:</b> ". $z_row['workshop_title'] ."</td><td align='right' colspan='2' width=300 valign=top>" . $qty_insert . " at ". $z_row['workshop_price'] ." each: </td><td valign=top> $". $qty_total ."</td></tr>"; I have the following code: Code: [Select] private function buildJSResponse(){ $data = ""; $i = 0; $arr = array(); while($this->db->row()){ $arr[] = (int)$this->db->field("average"); } $this->max = max($arr); $this->min = min($arr); $this->mid = round(($this->max + $this->min) / 2); foreach($arr as $val){ $nTime = ($val / $this->max) * 100; $data .= "data[$i] = ".$nTime.";"; $i++; } return $data; } It takes an array, finds the max/min and number halfway between the min/max. The next part I am not sure what to do. I am making a line graph using the canvas, so I am building a javascript array, which will contain the point on the chart. The problem I am having, is location. Lets say $max = 110, and $min = 95. the y position on the graph should be 0 for $max, and 100 for $min, then all the other points need to fall into their place as well. $nTime is supposed to do that, but it doesn't any suggestions? The attachment is the result I am getting from my above code. As you can see the lowest number is 49, so the value with 49 should touch the bottom, which it doesn't. I'm using the restrict content pro plugin to accept website registrations. I would like users to have the ability to click a checkbox on the registration page and it automatically applies a $50 discount. I am using this code to add a checkbox to the registration field, but I'm having trouble applying the "RCP_Discount" class when the box is checked. Any help would be greatly appreciated. Thank you! ~Sarah Hey Guys, So I'm stuck on a particular line of PHP for woocommerce the code I have hear works for doing 2 levels of discount. 1 - The discount code in woocommerce coupon settings gives - 10% off for products in category named "10OFF" - Coupon settings are in the image below 2. This code here then allows the same coupon to give 15% off off products in category named "15OFF" 3. What I can't seem to work out, is how to add another layer to this, where the same coupon will give 35% off products in a category named "35OFF" I get the feeling this is something really super obvious to someone who knows more about PHP coding than myself! I've tried multiple IF statements, that breaks the whole thing. I'm confident Creating multiple Categories is the way forward. I just can't work out how to add the new categories to the code that doesn't suddenly break the whole thing again stopping all discounts being taken off each item. Any advice would be hugely appreciated! I know the Code could be a lot neater in general, but I'm really new to PHP Kind Regards to all Liam add_filter( 'woocommerce_coupon_get_discount_amount', 'alter_shop_coupon_data', 20, 5 ); function alter_shop_coupon_data( $round, $discounting_amount, $cart_item, $single, $coupon ){ //Settings// $coupon_codes = array('bigsavings'); // Product categories at 15% $product_category15 = array('15off'); // for 15% discount $second_percentage = 0.015; // 15 % // Code// if ( $coupon->is_type('percent') && in_array( $coupon->get_code(), $coupon_codes ) ) { if( has_term( $product_category15, 'product_cat', $cart_item['product_id'] ) ){ $original_coupon_amount = (float) $coupon->get_amount(); $discount = $original_coupon_amount * $second_percentage * $discounting_amount; $round = round( min( $discount, $discounting_amount ), wc_get_rounding_precision() ); } } return $round; }
Edited May 17 by liamhluk Additional info on what I've tried already Hi, I am trying to figure out how to stop my script from offering a discount when the date that is listed passes by. It seems to always 'reset' itself even after the 15th of the month...I want it to stop after April 15...This is what I had, can anyone assist? Thank you in advance for your help! Jennifer Code: [Select] } if(date("n") < 15) { $before = $cost*.05; $before = round($before,2); $cost = $cost-$before; } I asked this once b4 and the answer seemed to work but now the discount is being caclulated again...I wanted the discount to stop after April 15...The below code doesn't work, can someone help??? Code: [Select] } if(date("j") < 14) { $before = $cost*.05; $before = round($before,2); $cost = $cost-$before; } Thank you in advance for ANY help that can be provided. Jennifer Hello,
I am not very good at javascript.
Actually i have form like this
<td> <input type="text" name="item[]" id="category" value="<?php echo $row1['item'];?>" /></td> <td> <input type="text" name="uom[]" class="span2" value="<?php echo $row1['uom'];?>" /></td> <td> <input type="text" name="description[]" value="<?php echo $row1['description'];?>" /></td> <td><input type="text" class="jQinv_item_qty span1" name="quantity[]" /></td> <td><input type="text" class="jQinv_item_unit span1" name="price[]" value="<?php echo $row1['selling_price'];?>" /></td> <td><select name="tax[]" class="jQinv_item_tax span1"> <option value="<?php echo $row1['tax'];?>"><?php echo $row1['tax'];?></option> <?php $l1 = mysql_query("select * from taxes") or die (mysql_error()); while($l2 = mysql_fetch_array($l1)) { ?> <option value="<?php echo $l2['rate']; ?>"> <?php echo $l2['name'];?> - <?php echo $l2['rate'];?>% </option> <?php } ?> </select></td> <td> <input type="text" class="jQinv_item_discount span1" name="discount[]" value="<?php echo $row1['discount'];?>" /></td> <td><input type="text" class="jQinv_item_frt span1" name="freight[]" placeholder="Freight" /></td> <td><input type="text" class="jQinv_item_frtax span1" name="freight_tax[]" placeholder="Frt Tax" /></td> <td><input type="text" class="jQinv_item_total span2" name="total[]" /></td> a =( ((Quantity * Price) - Discount) * (tax/100) ) + Freight + (Freight * (Freight tax/100))I tried doing like this, But it did not work at all function rowInputs() { var balance = 0; var subTotal = 0; var taxTotal = 0; $(".invE_table tr").not('.last_row').each(function () { var $unit_price = $('.jQinv_item_unit', this).val(); var $qty = $('.jQinv_item_qty', this).val(); var $tax = $('.jQinv_item_tax', this).val(); var $discount = $('.jQinv_item_discount', this).val(); var $frt = $('.jQinv_item_frt', this).val(); var $frtax = $('.jQinv_item_frtax', this).val(); var $total = (($unit_price * 1) * ($qty * 1))- $discount; var $tax_amount = (($total) *($tax/parseFloat("100"))); var $total_amount = (($tax_amount) + ($frt)) + $frtax; var parsedTotal = parseFloat( ('0' + $total_amount).replace(/[^0-9-\.]/g, ''), 10 ); var parsedTax = parseFloat( ('0' + $tax_amount).replace(/[^0-9-\.]/g, ''), 10 ); var parsedSubTotal = parseFloat( ('0' + $total).replace(/[^0-9-\.]/g, ''), 10 ); $('.jQinv_item_total',this).val(parsedTotal.toFixed(2)); subTotal += parsedSubTotal; taxTotal += parsedTax; balance += parsedTotal; }); var discount = parseFloat( ('0' + $('#inv_discount').val()).replace(/[^0-9-\.]/g, ''), 10 ); var balance_disc = balance - discount; $(".invE_subtotal span").html(subTotal.toFixed(2)); $(".invE_tax span").html(taxTotal.toFixed(2)); $(".invE_discount span").html(discount.toFixed(2)); $(".invE_balance span").html(balance_disc.toFixed(2)); } Trying to get the percentage of rent for a property in php. Im completely lost .... Code: [Select] <?php $purchase = 44000; $rent = 9860; $percent = $purchase * $rent; //this is wrong, it returns 4.3 but should be over 18 echo "Percentage is {$percent}%"; ?> Hello Everyone, I'm a newbie trying to improve my script below. The script works fine but I would like to add the 3 radio buttons computations enhancements Ergo, if a user chooses 'Matte Paper" a 10% would be added to the Price Quote result. If a user chooses ' Gloss Paper, a 10% would be added to the Price Quote result. If a user chooses 'Canvas" , a 20 % would be added to the Price Quote result. If someone could assist with the math or post me a helpful link it would be greatly appreciated. Thank you. Paul from Melbourne, Australia. <div style="border:dashed 1px; width:570px;"> <form method="post" action="<?php echo $_SERVER['php_SELF'];?>"> <p> 1. Enter the size (100w.x180h. cm) you want your picture printed: Width <input type="text" name="width" size="1" maxlength="3" value="0" onFocus="this.value=''; this.style.color='#ff0000';"> Height <input type="text" name="height" size="1" value="0" maxlength="3" value="0" onFocus="this.value=''; this.style.color='#ff0000';"> </p> <p> 2. Choose the printing material for your pictu <input type="radio" value="cms in Matte paper" name="material" size="3" maxlength="3" /> Matte Paper <input type="radio" value="cms in Gloss Paper:" name="material" size="3" maxlength="3" /> Gloss Paper <input type="radio" value="cms in Canvas:" name="material" size="3" maxlength="3" /> Canvas </p> <p> 3. Submit your info for our Price Quote below : <input type="submit" name="submit" value="Submit" /> or: <input type="submit" name="clear" value="Reset" /> </p> <p> 5. Our Price Quote to print your artwork sized: <?php $width = $_POST['width']; /* if artwork wider than 101 cm no quote, exits*/ if ($width >=101) {echo "Error!"; exit ;} $height = $_POST['height']; /* if artwork higher than 181 cm no quote, script exits */ if ($height >=181) {echo "Error!"; exit ;} $measurement = $_POST['measurement']; $material = $_POST['material']; $result = $width * $height; echo " $width x $height $material is: "; echo "$".number_format($result,2). "" ; ?> </p> </form> </div> I am trying to create a math equation inside a variable but I am struggling to achieve the desired result. On one php page I have this:
$x = "date('Y')"; On my main page I have linked to the above and also $description but the result I am getting is: In this classic lecture which was delivered over date('Y') - 1989 years ago,
I want to create a variable so I don't need to go back every year and change the description. Is this possible? Robert
Hi guys. I'm using php to randomly generate a simple math verification question. But, I'm having a hard time validating the input. Can someone please tell me what I'm doing wrong? Thank you } else if(trim($verify) != $_SESSION['UserData']['Math'][0]+$_SESSION['UserData']['Math'][1]){ $error = '<div class="error_message">Attention! The verification number you entered is incorrect.</div>'; } <?php echo "<span class='label'><span class='required'>*</span>What is ".$_SESSION['UserData']['Math'][0]." + ".$_SESSION['UserData']['Math'][1]."?</span> "; ?> <input name="verify" type="text" id="verify" size="3" value="<?=$verify;?>" /><br /><br /> Hi, I am TheMeq. I am currently developing a Text-Based MMORPG in PHP/MySQL. I have quite alot of the code laid down, its just this bit that is starting to throw me a bit. I've been working on it since 8am this morning.. it is now 4:30pm and i think it's nearly there. It's just not working the way I would like. So if I was to ask for help, should I just post what code I have? is there a math function that give you an integer value when u divide 2 numbers? ie in 7/3 i just want 2 as a result not floating number. thanks in advance. I'm trying to make a script to check a files date time and if its under so many seconds long the page will refresh. here is what I've got. I've been testing the output of the date() functions but when i do the math all i get is a 0. where did i go wrong? is it just i can't do math with dates? Thanks in advanced. Code: [Select] <html><head> <meta http-Equiv="Cache-Control" Content="no-cache"> <meta http-Equiv="Pragma" Content="no-cache"> <meta http-Equiv="Expires" Content="0"> <? $proFile = "profilePics/profile.jpg"; //if ( date ("m d Y H:i:s.") - date ("m d Y H:i:s.", filemtime($proFile)) <= 00 00 0000 00:00:04 ){ //this is where the magic should happen. //echo "<meta http-equiv="refresh" content='4'>"; } ?> </head> <? echo date ("m d Y H:i:s."); echo "<br>"; echo date ("m d Y H:i:s.", filemtime($proFile)); echo "<br>"; echo date ("m d Y H:i:s.") - date ("m d Y H:i:s.", filemtime($proFile)); //only outputs 0 ?> The title may not fit but only thing i could think of. I am pulling data from MSSQL database table.... I need everything from that table but i need to do some basic math funcitons to the resulting data. So the quesiton is should i do the math for this in the SQL query if so how do i pull all fields and do the math in an effcient way. Or should i let php do the math for me after i get all the data i need. If it is better to use php how can i do this in a while loop and get the math result and not a printed equation. Just looking for a few pointers never had to do math before with php In a past post I mentioned that my ultimate goal of this is code is to query our SQL system for a start date and a stop date. At both of those points, the query would spit out a value for that the column based on a determined time and day. The first point would be a min or minUsage. The second point would be max or maxUsage. These points will be subtracted from each other to create a value. See below. Not that it matters but the value is the amount of kWh per months.
So, now, Min and Max are both defined below but I suspect the value is being truncated for each. Also, Im not sure the calculation is right because I am getting an unexpected solution. I am asking that someone look at this code and tell me what should be happening mathematically. (down to the accuracy of the answer (pre calculation and post calculation) It would help me better see my mistakes.
To give you an example of some data. I have
Max ( or July 31)
total_energy_a =26872
total_energy_b =27619
total_energy_c =26175
Min ( or July 1)
total_energy_a =20347
total_energy_a =20914
total_energy_a =19808
Max - Min
19597
With these numbers, would you expect this outcome from this code?
Thanks.
<?php $sql = ";WITH TOTAL_KWH_SUMMER AS ( SELECT CONVERT(VARCHAR(10),cdate,111)AS trans_date, datepart(hh, cdate) as trans_hour, comm_id, MIN((total_energy_a+total_energy_b+total_energy_c)/100) AS minUsage, MAX((total_energy_a+total_energy_b+total_energy_c)/100) as maxUsage, repeated FROM [radiogates].[dbo].[purge_data] where comm_id='$comm_id' group by comm_id, CONVERT(VARCHAR(10),cdate,111), datepart(hh, cdate), repeated ) SELECT *, datepart(weekday, trans_date) as trans_date_day, datepart(month, trans_date) as trans_date_month, maxUsage - minUsage as totalUsage FROM TOTAL_KWH_SUMMER where datepart(weekday, trans_date) IN ('1', '2', '3', '4', '5', '6', '7') AND DATEPART(MONTH, trans_date) IN ('5','6','7','8','9','10') and trans_date BETWEEN '$startdate2 00:00:01' AND '$enddate2 24:00:00' and repeated <> '1' "; $query = sqlsrv_query($conn, $sql);if ($query === false){ exit("<pre>".print_r(sqlsrv_errors(), true));}while ($row = sqlsrv_fetch_array($query)){ $sumUsageKWH += $row[totalUsage];}sqlsrv_free_stmt($query);?> With this code, I am trying to create a guessing game. When I press the START button, I want it display a guess, highest, and the lowest number between 1-100. The highest number being 100, and the lowest being 1. I'm trying to get the math formula to do this equation (Guess = round((Highest +Lowest))/2. Can any one give me a hand. Code: [Select] <head> <title> Project 3 </title> </head> <body> <h1>Guessing Game</h1> <form method='post' action=''> <input type='submit' name='start' id='start' value='Start Game'> <form method='post' action=''> <input type='submit' name='higher' id='higher' value='Higher'> <form method='post' action=''> <input type='submit' name='lower' id='lower' value='Lower'> <?php if (isset($_POST['start'])) { print"<input type = 'hidden' name = 'hdnCount' value = '$count'> <input type = 'hidden' name = 'hdntop' value = '$top'> <input type = 'hidden' name = 'hdnbottom' value = '$bottom'> <input type = 'hidden' name = 'hdnguess' value = '$guess'>"; } if (isset($_POST['higher'])) { $count = $_REQUEST["hdnCount"]; $top = $_REQUEST["hdntop"]; $bottom = $_REQUEST["hdnbottom"]; $guess = $_REQUEST["hdnguess"]; print" <input type = 'hidden' name = 'hdnCount' value = '$count'> <input type = 'hidden' name = 'hdntop' value = '$top'> <input type = 'hidden' name = 'hdnbottom' value = '$bottom'> <input type = 'hidden' name = 'hdnguess' value = '$guess'>"; } if (isset($_POST['lower'])) { $count = $_REQUEST["hdnCount"]; $top = $_REQUEST["hdntop"]; $bottom = $_REQUEST["hdnbottom"]; $guess = $_REQUEST["hdnguess"]; print" <input type = 'hidden' name = 'hdnCount' value = '$count'> <input type = 'hidden' name = 'hdntop' value = '$top'> <input type = 'hidden' name = 'hdnbottom' value = '$bottom'> <input type = 'hidden' name = 'hdnguess' value = '$guess'>"; } ?> </form> </body> </html> This topic has been moved to PHP Math Help. http://www.phpfreaks.com/forums/index.php?topic=310665.0 I can' t even get the simple str_replace to work. I got.... $rslt = $client->getTodaySubIDStats($key, $sub_id); $rslt = str_replace("EARNINGS",'',$rslt); $rslt = str_replace("Array","",$rslt); $rslt = str_replace("\r","",$rslt); $rslt = str_replace("\n","",$rslt); $rslt = str_replace("\t","",$rslt); print_r($rslt); which spits out.... Code: [Select] Array ( [0] => Array ( [EARNINGS] => $100.40 [CLICKS] => 1301 [LEADS] => 100 [SUB_ID] => yacker [EPC] => $0.11 ) ) I would like to have every thing removed except the '$100.40' (The number is always changing). Then remove the $ and do math 100.40*.40, so in the end, all it spits out is 40.16 and always only have two digits after the period. I'm using this code to get me the variables to a select box on a register page: $vars['user-birthdate-years'] = array(_VARS_USER_CHOOSE_ => "Please choose", _VARS_USER_NONE_ => _VARS_USER_UNDEF_); for ($i = date('Y') - 18; $i > date('Y') - 75; --$i) { $vars['user-birthdate-years'][$i] = "$i"; } This gives me this result in the page source: <select name="birthyear" class="date"><option value="-2" selected="selected">Please choose</option><option value="1997">1997</option><option value="1996">1996</option><option value="1995">1995</option><option value="1994">1994</option><option value="1993">1993</option><option value="1992">1992</option><option value="1991">1991</option><option value="1990">1990</option><option value="1989">1989</option><option value="1988">1988</option><option value="1987">1987</option><option value="1986">1986</option><option value="1985">1985</option><option value="1982">1982</option><option value="1981">1981</option><option value="1980">1980</option><option value="1979">1979</option><option value="1978">1978</option><option value="1977">1977</option><option value="1976">1976</option><option value="1975">1975</option><option value="1974">1974</option><option value="1973">1973</option><option value="1972">1972</option><option value="1971">1971</option><option value="1970">1970</option><option value="1969">1969</option><option value="1968">1968</option><option value="1967">1967</option><option value="1966">1966</option><option value="1965">1965</option><option value="1964">1964</option><option value="1963">1963</option><option value="1962">1962</option><option value="1961">1961</option><option value="1960">1960</option><option value="1959">1959</option><option value="1958">1958</option><option value="1957">1957</option><option value="1956">1956</option><option value="1955">1955</option><option value="1954">1954</option><option value="1953">1953</option><option value="1952">1952</option><option value="1951">1951</option><option value="1950">1950</option><option value="1949">1949</option><option value="1948">1948</option><option value="1947">1947</option><option value="1946">1946</option><option value="1945">1945</option><option value="1944">1944</option><option value="1943">1943</option><option value="1942">1942</option><option value="1941">1941</option></select> Problem: When running the php code at the top it miss two years in the span as you see in the page source below, the year 1983 and 1984 is completely missing in the page source. Why is this happening, could the php code be corrected or is there a workaround in php for the missing years bug I seem to have found? I really appreciate any help on this! Edited by Drezzzer, 12 January 2015 - 05:16 AM. |