【问题标题】:php showing error when getting the values from an arrayphp从数组中获取值时显示错误
【发布时间】:2012-11-24 07:55:38
【问题描述】:

在 php 中我的代码是这样的

  $discounts =  $this->model_catalog_product->getProductDiscounts($product_id);
      $product_discounts[] = array();
      foreach($discounts as $discount) {
        $product_discounts[] = array(
          'quantity' => $discount['quantity'],
          'price'    => $this->currency->format($this->tax->calculate($discount['price'], $product_info['tax_class_id'], $this->config->get('config_tax')))
        );
      }

现在当我让它显示我的数组时

Array ( [0] => Array ( [product_discount_id] => 483 [product_id] => 43 [customer_group_id] => 8 [quantity] => 2 [priority] => 1 [price] => 345.0000 [date_start] => 0000-00-00 [date_end] => 0000-00-00 ) [1] => Array ( [product_discount_id] => 484 [product_id] => 43 [customer_group_id] => 8 [quantity] => 4 [priority] => 2 [price] => 784.0000 [date_start] => 0000-00-00 [date_end] => 0000-00-00 ) [2] => Array ( [product_discount_id] => 485 [product_id] => 43 [customer_group_id] => 8 [quantity] => 5 [priority] => 3 [price] => 786.0000 [date_start] => 0000-00-00 [date_end] => 0000-00-00 ) )

但是当我编写代码以从数组中获取折扣数量和折扣价格的值时

 <?php foreach ($discounts as $discount) {
    echo sprintf($text_discount, $discount['quantity'], $discount['price']); ?>
    } ?>

我收到了这样的错误Undefined variable: discounts

【问题讨论】:

    标签: php arrays arraylist


    【解决方案1】:

    替换这个

    $product_discounts[] = array();
    

    $product_discounts = array();
    

    【讨论】:

    • 这实际上不是错误,也没有回答问题。
    【解决方案2】:

    $discounts 从未被定义。应该是$product_discounts。这就是为什么你会收到undefined variable discounts

    <?php
    foreach ($product_discounts as $discount) {
        echo sprintf($text_discount, $discount['quantity'], $discount['price']); ?>
    }?>
    

    【讨论】:

      【解决方案3】:

      试试这个

      $discounts =  $this->model_catalog_product->getProductDiscounts($product_id);
        $product_discounts = array();
        foreach($discounts as $discount) {
          $product_discounts = array(
            'quantity' => $discount['quantity'],
            'price'    => $this->currency->format($this->tax->calculate($discount['price'], $product_info['tax_class_id'], $this->config->get('config_tax')))
          );
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-10
        • 2018-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多