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}]

 

相关文章:

  • 2021-12-23
  • 2022-12-23
  • 2021-08-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
  • 2022-01-09
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-18
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案