Laravel 合并请求中子数组中的字段
Laravel merge field in sub-arrays in the request
我从请求中收到此数据:
array:2 [
0 => array:3 [
"from" => 0
"to" => 5
"earned" => 0
]
1 => array:3 [
"from" => 5
"to" => 10
"earned" => 1
]
]
我想将brand_id添加到每个子数组。
我知道我可以将字段合并到请求中,例如:
$request->merge([
'brand_id' => $brand_id,
]);
这导致:
array:3 [
0 => array:3 [
"from" => 0
"to" => 5
"earned" => 0
]
1 => array:3 [
"from" => 5
"to" => 10
"earned" => 1
]
"brand_id" => "1"
]
我想要的结果是:
array:2 [
0 => array:4 [
"from" => 0
"to" => 5
"earned" => 0
"brand_id" => "1"
]
1 => array:4 [
"from" => 5
"to" => 10
"earned" => 1
"brand_id" => "1"
]
]
要是能这样就好了:
$request->merge([
'*.brand_id' => $brand_id,
]);
注意:我已经检查过这个 但如果我要使用 foreach,我将不需要进行请求合并。此外,Laravel 8.
可能还有一些新内容
试试下面的代码。您可以迭代每个元素并合并。 (假设您使用的是请求对象)
$mergedArray = array_map(function($element) use ($brand_id){
return array_merge($element, ['brand_id' => $brand_id]);
}, $request->all())
我从请求中收到此数据:
array:2 [
0 => array:3 [
"from" => 0
"to" => 5
"earned" => 0
]
1 => array:3 [
"from" => 5
"to" => 10
"earned" => 1
]
]
我想将brand_id添加到每个子数组。
我知道我可以将字段合并到请求中,例如:
$request->merge([
'brand_id' => $brand_id,
]);
这导致:
array:3 [
0 => array:3 [
"from" => 0
"to" => 5
"earned" => 0
]
1 => array:3 [
"from" => 5
"to" => 10
"earned" => 1
]
"brand_id" => "1"
]
我想要的结果是:
array:2 [
0 => array:4 [
"from" => 0
"to" => 5
"earned" => 0
"brand_id" => "1"
]
1 => array:4 [
"from" => 5
"to" => 10
"earned" => 1
"brand_id" => "1"
]
]
要是能这样就好了:
$request->merge([
'*.brand_id' => $brand_id,
]);
注意:我已经检查过这个
试试下面的代码。您可以迭代每个元素并合并。 (假设您使用的是请求对象)
$mergedArray = array_map(function($element) use ($brand_id){
return array_merge($element, ['brand_id' => $brand_id]);
}, $request->all())