1、业务场景:创建订单创建成功,把订单id添加到每个详情数据中
  1. $orderItem = [
  2. [
  3. 'goods_name' => '苹果',
  4. 'num' => 1
  5. ],
  6. [
  7. 'goods_name' => '香蕉',
  8. 'num' => 2
  9. ],
  10. ];

2、使用array_walk() 给上面的数组添加一个元素 ‘order_id’ => 10

  1. $order = ['order_id' => 10];
  2. array_walk($orderItem, function (&$value, $key, $order) {
  3. $value = array_merge($value, $order);
  4. }, $order);
  5. dump($orderItem);
  6. # 输出
  7. $orderItem = [
  8. [
  9. 'goods_name' => '苹果',
  10. 'num' => 1,
  11. 'order_id' => 10
  12. ],
  13. [
  14. 'goods_name' => '香蕉',
  15. 'num' => 2,
  16. 'order_id' => 10
  17. ],
  18. ];

3、函数array_walk() 解释

对数组中每个元素调用,自定义的函数,并返回新的数组