有实例代码如下:
// 有一个产品分为标准版和高级版 $products = [ 'standard' => [ 'price' => 100, // 原价 'discount' => 0.8, // 折扣 ], 'advanced' => [ 'price' => 200, 'discount' => 0.7, ], ]; // 算出节省的金额 foreach ($products as &$product) { $product['save'] = $product['price'] * (1 - $product['discount']); } // 输出产品价格信息 foreach ($products as $product) { print_r($product); }
运行,输出的结果却是:
$ php test_foreach.php Array ( [price] => 100 [discount] => 0.8 [save] => 20 ) Array ( [price] => 100 [discount] => 0.8 [save] => 20 )
不知道看官您看出问题没有,找这个问题花了我老长时间,foreach 里面对值使用使用后,loop 结束,值还存在,所以在 foreach 循环结束后应手动 unset 该变量。
改正后的 PHP 代码为:
$products = [ 'standard' => [ 'price' => 100, 'discount' => 0.8, ], 'advanced' => [ 'price' => 200, 'discount' => 0.7, ], ]; foreach ($products as &$product) { $product['save'] = $product['price'] * (1 - $product['discount']); } unset($product); // ******** <--注意这里!!! ********** foreach ($products as $product) { print_r($product); }
php.net 上关于 foreach 里面使用引用的警告说明如下:
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
是要手动 unset 这个变量的—— zhousenbiao.com