0

我在类的 foreach 中使用数组时遇到问题。我收到警告..

PHP 警告:为 foreach() 提供的参数无效

在线的

foreach($this->recordOfDiscounts as $key => $discount)

有问题的功能如下,

public function modify_price( $price, $product_id ) {
    foreach($this->recordOfDiscounts as $key => $discount) {
        foreach($discount['get_one_free'] as $id) {
            if($id == $product_id){
                if( $discount['valid'] > 0 ) {
                    $price -= $discount['cost'];
                    $this->recordOfDiscounts[$key]['valid'] -= 1;
                }
            }
        }
    }
    return $price;
}

我是 PHP 新手,但我收集到的是类作用域 ( $this->) 需要在类中添加一个 var 前缀。

error_log(print_r($this->recordOfDiscounts),0);

输出正确的数组信息,所以我知道它的定义。

Array
(
    [0] => Array
        (
            [valid] => 1
            [buy_one] => 2351
            [cost] => 20
            [old_cost] => 20
            [get_one_free] => Array
                (
                    [0] => 2471
                    [1] => 2470
                    [2] => 2472
                    [3] => 2473
                    [4] => 2474
                    [5] => 2475
                    [6] => 2476
                    [7] => 2477
                )

        )

)
4

1 回答 1

2

其中一个 foreach 语句具有不可迭代的内容作为语句的第一部分。

要么$this->recordOfDiscounts不是数组,要么在外部 foreach 的一次迭代中$discount['get_one_free']不可迭代。

于 2013-01-09T11:00:07.073 回答