sasori
sasori

Reputation: 5455

how to loop through this array and get the sum?

I got stuck, my objective was to get the ProductID, hidden inside the $_SESSION['cart'] and then use those ID in an sql query to compute the sum

here's my code

public function getProductID(){
    $keys = array_keys($_SESSION['cart']);
    return $keys;
}


public function getShippingFee(){
    $ids = $this->getProductID();
    foreach($ids as $id){
    $query = mysql_query("SELECT * FROM deliverycharges WHERE ProductID = $id");
    $row = mysql_fetch_assoct($query);
    $sum = $row['Cost'] + $row['Tax'];
    return $sum;   
  }
}

the second function that I pasted is wrong, I have done several type of looping and yet, I can't get the real sum..shame on me

Upvotes: 2

Views: 969

Answers (2)

Nick Garvey
Nick Garvey

Reputation: 3000

You are overwriting the value of sum each loop. Use +=

public function getShippingFee() {
    $ids = $this->getProductID();
    $sum = 0;
    foreach($ids as $id) {
        $query = mysql_query("SELECT * FROM deliverycharges WHERE ProductID = $id");
        $row = mysql_fetch_assoct($query);
        $sum += $row['Cost'] + $row['Tax'];
    }
    return $sum;   
}

Upvotes: 0

bardiir
bardiir

Reputation: 14782

After you return, the function is exited, so you need to sum everything up at first and then return that after everything is summed up:

public function getShippingFee(){
    $ids = $this->getProductID();
    foreach($ids as $id){
      $query = mysql_query("SELECT * FROM deliverycharges WHERE ProductID = $id");
      $row = mysql_fetch_assoc($query);
      $sum += $row['Cost'] + $row['Tax'];
    }
    return $sum; 
}

Upvotes: 6

Related Questions