1、业务场景:创建订单创建成功,把订单id添加到每个详情数据中
$orderItem = [
[
'goods_name' => '苹果',
'num' => 1
],
[
'goods_name' => '香蕉',
'num' => 2
],
];
2、使用array_walk() 给上面的数组添加一个元素 ‘order_id’ => 10
$order = ['order_id' => 10];
array_walk($orderItem, function (&$value, $key, $order) {
$value = array_merge($value, $order);
}, $order);
dump($orderItem);
# 输出
$orderItem = [
[
'goods_name' => '苹果',
'num' => 1,
'order_id' => 10
],
[
'goods_name' => '香蕉',
'num' => 2,
'order_id' => 10
],
];
3、函数array_walk() 解释
对数组中每个元素调用,自定义的函数,并返回新的数组