calculating subtotal and total from basic shopping cart script - php

Im trying to calculate a subtotal and a total from a series of values stored in an array returned from a mysql database.
this i what i have thusfar
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
foreach( $contents as $key => $value){
if($key == "price"){$subtotal = $subtotal+$value;}
echo "$key : $value <br />";
}
echo "<br><br><br>";
}
echo "<font color=red>SubTotal $subtotal</font>";
$contents contains an array [name] => super [price] => 65.87 [quantity] => 25
So i need to multiply the price by quantity, and then take that subtotal (per item) and add it in total after the loop

foreach( $contents as $key => $value)
{
if($key == "price") $total = $total+$value;
if($key == "name")
{
if(!isset($subtotal[$key])) $subtotal[$key] = 0;
$subtotal[$key] = $subtotal[$key] + $value;
}
}
Then you have total price in $total and for each individual item in $subtotal array

I'm not sure what you mean for total and subtotal. I assume that subtotal is the price of an item times his quantity.
For Total I assume you intend the subtotal you print in red.
Your code become:
$total=0;
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
$contents['subtotal'] = $contents['price']*$contents['quantity'];
foreach($contents as $key => $value){echo "$key : $value <br />"; }
$total +=$content['subtotal'];
}
echo "<font color=red>Total: $total</font>";
If the formatting is not mandatory I would use a slight different solution
for formatting the output. (you should check the printf format string placeholder syntax)
$billLine = "%s (%0.2f x %d): %0.2f<br /><br /><br />";
$total=0;
while($row = mysql_fetch_array($cart)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$contents = unserialize($row['contents']);
$subtotal = $contents['price']*$contents['quantity'];
printf($billLine, $contents['name'],
$contents['quantity'],
$contents['price'],
$subtotal);
$total +=$subtotal;
}
echo "<font color=red>Total: $total</font>";

Related

Eliminating duplicating value in 2D array in php

I can't attach images so please find array at link.
I eliminated the duplicated value for this array. I used technique that is bit awful. Array name is $pap.
Here is code
`foreach ($pap as $key => $row)
{
foreach ($row as $subkey => $subvalue)
{ $p[$n]=$pap[$key][$subkey];
$n++;
}
}
$unique = array_unique($p);
$n=0; $abc = array();
foreach ($unique as $key => $row){
$abc[$n]=$unique[$key]; $n++;
}
$m=0;
echo "<table align='center' border='2'>";
foreach ($pap as $key => $row)
{
echo "<tr>";
foreach ($row as $subkey => $subvalue)
{
if($m<$n){
if($pap[$key][$subkey]==$abc[$m])
{
echo "<td>";
echo $pap[$key][$subkey];
echo "</td>";
$m++;
}
}
}
echo "</tr>";
}
echo"</table>";`
Any better technique would be appreciated.
Check this, I think you this will do the job for you.
<?php
$details = array(
0 => array("id"=>"1", "name"=>"Mike", "num"=>"9876543210"),
1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
2 => array("id"=>"1", "name"=>"Mathew", "num"=>"784581254"),
);
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value)
{
if ( is_array($value) )
{
$result[$key] = super_unique($value);
}
}
return $result;
}
var_dump(super_unique($details));
?>

How can i get sum of the values of an array where array index value starts with same value?

Here are my two arrays.
This array is $assesment I have tried the code given below and got $cat_array.
foreach($assesment as $k => $v){
$k2 = explode("_",$k);
/* echo "cat : ".$cat = $k2[0] ."-". $v;
echo "<br>";
echo "Que : ".$que = $k2[1]."-". $v;
echo "<br>"; */
$cat_array[] = $k2[0]."-".$v;
}
print_r($cat_array);
Just update your loop like as
$cat_array = array();
foreach($assesment as $k => $v){
$k2 = explode("_",$k);
if(isset($cat_array[$k2[0]])){
$cat_array[$k2[0]] += $v;
}else{
$cat_array[$k2[0]] = $v;
}
}

Calculate max, min, and average for every column in a 2D array

I'm calculating the average,min,max for each column.
The 16th column value is coming wrong for max and min. Average is working perfectly fine, but wrong only for the last column with large arrays -- I also get a notice error.
My code:
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("db");
$qry = mysql_query("select blob_field from table where id=1");
$arr = mysql_fetch_row($qry) ;
$rt = explode("\n",$arr[0]);
$header_arr1 = explode(',',$rt[0]);
$header1 = array();
$channels = count($header_arr1)-2 ;
$header1[] = join(',', array_slice($header_arr1, 2));
//Only Header
$arr_values = array_values($rt);
$array_slice = array_slice($arr_values, 1);
echo "<pre>";
//print_r($array_slice);
$result_array = array();
for($i=0;$i<count($array_slice);$i++)
{
//echo $i;
$result_array[] = join(',',array_slice(explode(',', $array_slice[$i]), 2));
}
//print_r($result_array);
//$array_combined = array_merge($header1,$result_array);
$token = array( 'Average', 'Max', 'Min');
foreach($result_array as $key=>$val)
{
$res_arr[] = explode(",",$val);
}
$avArray = array();
$res_arr= array(
0=>array(1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18),
1=>array(17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18),
2=>array(17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108),
);
foreach ($res_arr as $k=>$subArray)
{
foreach ($subArray as $id=>$value)
{
//print_r($id);
$avArray[$id] += $value/count($res_arr); //Notice: Undefined offset: 3
}
}
$token = array( 'Average', 'Max', 'Min');
$num = $avArray;
$tc=16;
?>
<table border="1" style="border-collapse: collapse;">
<thead>
<tr>
<th>Channels</th>
<?php for($j=0;$j<=$tc-1;$j++):?>
<th>CH<?= $j+1;?></th>
<?php endfor;?>
</tr>
</thead>
<tbody>
<?php
echo "<tr><td>Average</td>";
for($i=0; $i<=$tc-1;$i++)
{
echo "<td>" .round($num[$i],2). "</td>";
}
echo "<tr><td>Max</td>";
$arr_max = array();
foreach($res_arr as $subArray)
{
foreach($subArray as $k=>$v) {
$arr_max[$k][] = $v;
}
}
$max_array = array_map('max', $arr_max);
for($i=0; $i<=$tc-1;$i++)
{
echo "<td>" .$max_array[$i]. "</td>";
}
echo "<tr><td>Min</td>";
$arr_min = array();
foreach($res_arr as $subArray)
{
foreach($subArray as $k=>$v1) {
$arr_min[$k][] = $v1;
}
}
$min_array = array_map('min', $arr_min);
for($g=0; $g<= $tc-1;$g++)
{
echo "<td>" .$min_array[$g]. "</td>";
}
?>
</tbody>
</table>
See inline comments for explanation.
$avArray = array();
$res_arr= array(
0=>array(1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18),
1=>array(17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18),
2=>array(17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108),
);
/*
foreach ($res_arr as $k=>$subArray){
foreach ($subArray as $id=>$value){
// this causes "Notice: Undefined offset: 0...15" because you can't add to an undeclared value
$avArray[$id] += $value/count($res_arr);
}
}
*/
$res_count=count($res_arr); // declare this outside of the loop for efficiency
foreach ($res_arr as $k=>$subArray){
foreach ($subArray as $id=>$value){
if($k==0){
$avArray[$id]=$value; // declare first round of values
}else{
$avArray[$id]+=$value; // add to existing values
if($k==2){
$avArray[$id]=$avArray[$id]/$res_count; // only divide on the last iteration
}
}
}
}
print_r($avArray);
No matter how you want to present it, you are going to have to loop over the data set more than one. Once to calculate and once to display.
Here is another snippet: (Demo)
$array = [
[1,2,3,6,7,8,9,11,33,44,55,66,77,88,16,18],
[17,52,38,666,79,8,9,15,33,44,55,66,76,88,16,18],
[17,562,538,7666,579,688,9,15,933,44,55,660,76,808,106,108],
];
$count = count($array);
$mins = [];
$maxs = [];
$avgs = [];
foreach ($array as $i => $row) {
foreach ($row as $col => $value) {
$ch = $col + 1;
if (!$i) {
$mins[$ch] = $value;
$maxs[$ch] = $value;
$avgs[$ch] = $value;
} else {
if ($value < $mins[$ch]) {
$mins[$ch] = $value;
}
if ($value > $maxs[$ch]) {
$maxs[$ch] = $value;
}
$avgs[$ch] += $value;
if ($i === $count - 1) {
$avgs[$ch] = number_format($avgs[$ch] / $count, 2);
}
}
}
}
echo '<table border=1>';
printf(
'<tr><th>Channels</th><th>CH%s</th></tr>',
implode('</th><th>CH', array_keys($avgs))
);
printf(
'<tr><th>Average</th><td>%s</td></tr>',
implode('</td><td>', $avgs)
);
printf(
'<tr><th>Max</th><th>%s</td></tr>',
implode('</td><td>', $maxs)
);
printf(
'<tr><th>Min</th><td>%s</td></tr>',
implode('</td><td>', $mins)
);
echo '</table>';

php foreach error handling in function

I have a function which performs a foreach loop on an array from a database.
see foreach ($teamarray AS $key => $value){$teamgo .= $value[1]." ".$value[2]."<br/>";
Problem is, sometimes there may be no data set, which throws an error when the loop hits that field.
How can i catch/suppress this error?
function GetUnsubmitted($coach){
$push .= "<div id=unsubmitted><h2>Check which event/teams you want to process and click submit</h2>";
$push .= "<form action=\"submit.php\" method=POST>";
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]' AND status = '1' ORDER BY status ASC") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = DecodeTeam($teampre);
$price = GetPrice($type, "nat");
$teamcount = count($teamarray);
$total = $price * $teamcount;
$teamgo = "";
foreach ($teamarray AS $key => $value){
$teamgo .= $value[1]." ".$value[2]."<br/>";
if($statuspre == "1"){
$statuscolor = "#FFCC99";
$statusmsg = "unsubmitted <a href=delsub.php?id=$id onClick=\"return confirm('Are you sure you want to delete this submission?');\"><img src=images/del.png border=0 />";
} elseif($statuspre == "2"){
$statuscolor = "#FFCC66";
$statusmsg = "awaiting confirmation";
} elseif($statuspre == "3"){
$statuscolor = "#66CC66";
$statusmsg = "confirmed";
}
}
$push .= "<div id=submission><div id=event style=\"background-color:$statuscolor;\"><h1>$event</h1><span id=status>$statusmsg</span></div><div id=subinfo><span id=dropdown><img src=images/expand.png border=0></span><h2>$cat >> $subcat >> $division >> $type</h2> <div id=team style=\"display:none;\">$teamgo<br />$price - $total<div id=controls></div></div></div></div>";
$pid .= $id;
$rtotal .= "$total,";
}
$stotal = explode(",", $rtotal);
$gtotal = array_sum($stotal);
$push .= "<div style=\"text-align:right;\"><div id=total>Total - <em>$gtotal</em></div><br><input type=image src=images/paynow.png alt=\"Pay Now\"></form> <a href=submit2.php?$pid&$pidarray><img src=images/mailfax.png width=138px height=41px border=0></a></div></div>";
return $push;
}
If possible id like it to say "no team selected" and stop.
You can write so:
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
foreach expects array. So the really correct way is to ensure that you deal with array before try to iterate, like this:
if (is_array($teamarray) && count($teamarray)) {
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
}
You also can check is_iterable since PHP 7.1.
if ($array) {
foreach ($array as $k => $v) {
...
}
} else {
echo 'No team selected';
// exit from loop
}
Your exit from loop will be a "return", or a "break n" (n is the levels to break for) or continue... it depends on your logic.
if ($value !== null && count($value) >= 3) {
$teamgo .= $value[1] . $value[2]
}
<insert puzzled smiley here>
foreach($row AS $key => $value) {
if ($value) {
$row[$key] = stripslashes($value);
}
}
And:
foreach ($teamarray AS $key => $value){
if ($value && sizeof($value) > 2) {
$teamgo .= $value[1] . $value[2]
}
}
Is this it?
Just do a test if $teamarray actually is an array:
if (is_array($teamarray)) {
foreach ($teamarray as $key => $value) {
// …
}
}
Or you could do:
$teamarray = isset($teamarray) ? $teamarray : array();
Just prior to the loop in a nice tidy line, and it would ensure that you have the variable set to an empty array which would cause it to skip the foreach().

Looping through an array of arrays, changing output on a given line(s)

This is what im using to loop through an array of arrays.
$csvpre = explode("###", $data);
$i = 0;
$bgc = 0;
foreach ( $csvpre AS $key => $value){
$info = explode("%%", $value);
$i++;
if($i == "1"){
echo "<tr bgcolor=#efefef><td></td>";
foreach ( $info as $key => $value ){ echo "<td>$value</td>"; }
echo "</tr>";
} else {
if($bgc=1) { $bgcgo = "bgcolor=\"#b9b9b9\"" ;} else { $bgcgo = "bgcolor=\"#d6d6d6\""; }
echo "<tr $bgcgo><td></td>";
foreach ( $info as $key => $value ){ echo "<td>$value</td>"; }
echo "</tr>";
$bgc++;
}
}
How can i add an if/elseif statement to the last foreach, so that the output changes on a given line of the array.
Say i want <td>$value</td> for all unless specified, but on line 30, i want <textarea>$value</textarea>
You mean like this:
<?php
.......
echo "<tr $bgcgo><td></td>";
$j = 0; //you need a counter
foreach ( $info as $key => $value ) {
$j++;
if ($j != 30) {
echo "<td>$value</td>";
} else {
echo "<textarea>$value</textarea>";
}
}
echo "</tr>";

Categories