Laravel 常用辅助函数
辅助函数
Laravel 包含各种全局辅助函数。
laravel 中包含大量辅助函数,您可以使用它们来简化开发工作流程。
array_dot() 辅助函数允许你将多维数组转换为使用点符号的一维数组
$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_get() 函数使用点符号从多维数组中检索值
$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_add 函数添加给定键值对到数组 —— 如果给定键不存在的话
$array = array_add(['name' => 'Desk'], 'price', 100);
// ['name' => 'Desk', 'price' => 100]
array_collapse() 函数将多个数组合并成一个
$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_dot()
函数使用”.”号将将多维数组转化为一维数组
$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_except()
函数从数组中移除给定键值对
$array = ['name' => 'dark', 'age' => 20];
$result = array_except($array, ['name']);
dd($result);输出:
array:1 [▼"age" => 20
]
array_first()
函数返回通过测试数组的第一个元素
$array = ['name' => 'dark', 'age' => '31', 'sex' => 1];
$result = array_first($array, function ($key, $value) {return $key = 'name';
});
dd($result);输出:
"dark"
array_flatten()
函数将多维数组转化为一维数组
$array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];$array = array_flatten($array);// ['Joe', 'PHP', 'Ruby'];
array_forget()
函数使用”.”号从嵌套数组中移除给定键值对
$array = ['products' => ['desk' => ['price' => 100]]];array_forget($array, 'products.desk');// ['products' => []]
参考链接
https://blog.csdn.net/qq_25275355/article/details/126507724