Laravel 8 data_set() {#collection-method}
data_set
函数使用「.」符号给多维数组或对象赋值:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200);
// ['products' => ['desk' => ['price' => 200]]]
这个函数也支持使用「*」作为通配符给相应键名赋值:
$data = [
'products' => [
['name' => 'Desk 1', 'price' => 100],
['name' => 'Desk 2', 'price' => 150],
],
];
data_set($data, 'products.*.price', 200);
/*
[
'products' => [
['name' => 'Desk 1', 'price' => 200],
['name' => 'Desk 2', 'price' => 200],
],
]
*/
通常情况下,已存在的值将会被覆盖。如果只是希望设置一个目前不存在的值,你可以增加一个 false
作为函数的第四个参数:
$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, false);
// ['products' => ['desk' => ['price' => 100]]]