PHP foreach引用&
1、加引用,才可以改变原数组的值
$oProducts = [ ['product_id'=>1, 'count'=>3], ['product_id'=>2, 'count'=>3], ['product_id'=>3, 'count'=>3], ]; foreach($oProducts as &$p) { $p['order_id'] = 1; } return json($oProducts);
[{"product_id":1,"count":3,"order_id":1},{"product_id":2,"count":3,"order_id":1},{"product_id":3,"count":3,"order_id":1}]
2、如果不加引用,不能改变原数组的值
$oProducts = [ ['product_id'=>1, 'count'=>3], ['product_id'=>2, 'count'=>3], ['product_id'=>3, 'count'=>3], ]; foreach($oProducts as $p) { $p['order_id'] = 1; } return json($oProducts);
输出:
[{"product_id":1,"count":3},{"product_id":2,"count":3},{"product_id":3,"count":3}]
3、添加引用,相当于
$oProducts = [ ['product_id'=>1, 'count'=>3], ['product_id'=>2, 'count'=>3], ['product_id'=>3, 'count'=>3], ]; foreach($oProducts as $key=>$p) { $oProducts[$key]['order_id'] = 1; } return json($oProducts);
输出:
[{"product_id":1,"count":3,"order_id":1},{"product_id":2,"count":3,"order_id":1},{"product_id":3,"count":3,"order_id":1}]