一、加引用,才能夠改變原數組的值json
$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}]
二、若是不加引用,不能改變原數組的值數組
$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);
輸出:spa
[{"product_id":1,"count":3},{"product_id":2,"count":3},{"product_id":3,"count":3}]
三、添加引用,至關於code
$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);
輸出:blog
[{"product_id":1,"count":3,"order_id":1},{"product_id":2,"count":3,"order_id":1},{"product_id":3,"count":3,"order_id":1}]