Zulfakar Zukri
Zulfakar Zukri

Reputation: 173

get max value inside foreach PHP

i've set a shipping cost for the macbook to $5 and iphone to $1.50 and add this two product in the cart. and the php code below is to get those shipping cost from the database for each product on the cart

$cart_product = $this->cart->getProducts();
//$query = array();
$total = 0;

foreach ($cart_product as $product) {

  $query = $this->db->query("SELECT shipping_cost FROM " . DB_PREFIX . "shipping_cost WHERE product_id='" . (int)$product['product_id'] . "'");

  if ($query->rows) {
    if ($this->config->get('calculation_rules') == 'flatrate') {
      $total += $query->row['shipping_cost'];
      $shipping_cost = $total;
    }
  } else {
     $shipping_cost = $total;
  }

}

the above code will return a total shipping cost of $6.50 for flatrate as it should be. but suddenly today my client want the highest shipping cost only which is $5 from macbook without sum the shipping cost of iphone

i've read something similar from this (foreach max array value?) and try to achieve this outside of the foreach loop but it won't do the trick because the shipping cost is not come from the foreach loop it self. so how do get this to work?

just in case, here are my shipping_cost table structure looks like

product_id | shipping_cost
40         |    1.50     (iphone)
43         |    5.00     (macbook)

Upvotes: 0

Views: 2378

Answers (2)

linktoahref
linktoahref

Reputation: 7992

You could tweak your code to get the max shipping rate

$cart_product  = $this->cart->getProducts();
$shipping_cost = 0;
$total         = 0;
$min_value     = array();

foreach ($cart_product as $product) {

  $query = $this->db->query("SELECT shipping_cost FROM "
                 . DB_PREFIX . "shipping_cost WHERE product_id='" 
                 . (int)$product['product_id'] . "'");    

  if ($query->rows) {
    if ($this->config->get('calculation_rules') == 'flatrate') {
      $min_value[] = $query->row['shipping_cost'];
      if($shipping_cost < $query->row['shipping_cost']) {
          $shipping_cost = $query->row['shipping_cost'];
      }
    }
  } else {
     $shipping_cost = $total;
  }

}
$minimum_value = min($min_value);

Upvotes: 1

Mitali
Mitali

Reputation: 166

You can save shipping cost to array. and get the max value from array using php max function http://php.net/manual/en/function.max.php

Upvotes: 1

Related Questions