Laravel 包含各种全局辅助函数。
laravel 中包含大量辅助函数,您可以使用它们来简化开发工作流程。
$array = [
'user' => ['username' => 'something'],
'app' => ['creator' => ['name' => 'someone'], 'created' => 'today']
];
$dot_array = array_dot($array);
// [user.username] => something, [app.creator.name] => someone, [app.created] => today
$array = [
'user' => ['username' => 'something'],
'app' => ['creator' => ['name' => 'someone'], 'created' => 'today']
];
$name = array_get($array, 'app.creator.name');
// someone
如果 key
不存在,array_get()
函数还接受可选的第三个参数作为默认值。
$name = array_get($array, 'app.created.name', 'anonymous');
// anonymous
$array = array_add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
$array = array_collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
array_divide()
函数返回两个数组,一个包含原数组的所有键,另外一个包含原数组的所有值$result = array_divide(['name' => 'Desk']);
dd($result);
输出:
array:2 [▼
0 => array:1 [▼
0 => "name"
]
1 => array:1 [▼
0 => "Desk"
]
]
函数使用”.”号将将多维数组转化为一维数组$array = [
'products' => [
'desk' => ['price' => 100, 'sum' => 11],
'deal' => ['price' => 1000, 'sum' => 1001],
]
];
$result = array_dot($array);
dd($result);
输出:
array:4 [▼
"products.desk.price" => 100
"products.desk.sum" => 11
"products.deal.price" => 1000
"products.deal.sum" => 1001
]
函数从数组中移除给定键值对$array = ['name' => 'dark', 'age' => 20];
$result = array_except($array, ['name']);
dd($result);
输出:
array:1 [▼
"age" => 20
]
函数返回通过测试数组的第一个元素$array = ['name' => 'dark', 'age' => '31', 'sex' => 1];
$result = array_first($array, function ($key, $value) {
return $key = 'name';
});
dd($result);
输出:
"dark"
函数将多维数组转化为一维数组$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];
$array = array_flatten($array);
// ['Joe', 'PHP', 'Ruby'];
函数使用”.”号从嵌套数组中移除给定键值对$array = ['products' => ['desk' => ['price' => 100]]];
array_forget($array, 'products.desk');
// ['products' => []]
参考链接
https://blog.csdn.net/qq_25275355/article/details/126507724