在foreach PHP中获取最大值

时间:2016-02-17 04:34:05

标签: php foreach max opencart

我已经将macbook的运费设置为5美元,iphone设置为1.50美元,并将此两个产品添加到购物车中。以下php代码是从购物车上的每个产品的数据库中获取运费

$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;
  }

}

以上代码将为flatrate返回6.50美元的总运费。但突然今天我的客户想要最高的运费,只需5美元即可从macbook购买而无需支付iphone的运费

我已经阅读了类似的内容(foreach max array value?),并尝试在foreach循环之外实现这一点,但它不会成功,因为运费不是来自它自己的foreach循环。那么如何才能使这个工作?

以防万一,这里是我的shipping_cost表结构看起来像

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

2 个答案:

答案 0 :(得分:1)

您可以节省运费到阵列。并使用php max function http://php.net/manual/en/function.max.php

从数组中获取最大值

答案 1 :(得分:1)

您可以调整代码以获得最高运费

$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);