maybe basic math

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
swissbeets
Forum Newbie
Posts: 20
Joined: Thu Jun 26, 2008 7:56 pm

maybe basic math

Post by swissbeets »

i need to make a total for my shopping cart, but i am confused on how to save these values as i take them from a query

i am taking a query of all products selected, i get an array of productid,prodprice, etc

i want to take these values and multiply the price * qty but only where the product id's are the same

any suggestions?
i have started something but it is not working out at all
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: maybe basic math

Post by Benjamin »

Post what you've got so far.
swissbeets
Forum Newbie
Posts: 20
Joined: Thu Jun 26, 2008 7:56 pm

Re: maybe basic math

Post by swissbeets »

Code: Select all

 
while($row2 = mysql_fetch_array($result2))
{
 
 
$total = bcmul($row2['qty'], $row['product_price'], 1); 
 
echo $total;
}
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: maybe basic math

Post by Benjamin »

This will create a sub_totals array with the key as the product_id and the sub total as the value.

Code: Select all

 
 
$products = array();
 
while($row2 = mysql_fetch_array($result2))
{
    $products[$row2['productid']][] = $row2;
} 
 
$sub_totals = array();
 
foreach ($products as $product_id => $n)
{
    foreach ($products[$product_id] as $data)
    {
        $sub_totals[$product_id] += $data['price'];
    }
}
 
echo '<pre>' . print_r($sub_totals, true) . '</pre>';
 
swissbeets
Forum Newbie
Posts: 20
Joined: Thu Jun 26, 2008 7:56 pm

Re: maybe basic math

Post by swissbeets »

thank you but it displays this,
Array
(

)
i changed it to fit my db

Code: Select all

 
$query3= " SELECT *
                            FROM `cart`
                        WHERE cookie_id = ".$cookie_id;
                
    
                $result2 = mysql_query($query3);
        
 
 
 $products = array();
  
 while($row2 = mysql_fetch_array($result2))
 {
     $products[$row2['product_id']][] = $row2;
 }
  
 $sub_totals = array();
  
 foreach ($products as $product_id => $n)
 {
     foreach ($products[$product_id] as $data)
     {
         $sub_totals[$product_id] += $data['product_price'];
     }
 }
  
 echo '<pre>' . print_r($sub_totals, true) . '</pre>';
 
Post Reply