如何删除 PHP、Laravel 中包含值 white space 的键?
How can i remove the key which contain the value white space in PHP, Laravel?
public function store(Request $request)
{
$article = Article::create($request->only(['content']));
$categories = explode(",",$request->get('categories'));
$category_ids =[];
foreach ($categories as $category) {
$category_db = Category::where('name', trim($category))->firstOrCreate(['name'=> trim($category)]);
$category_ids [] = $category_db->id;
}
$article->category()->attach($category_ids);
return response("Successfully Added to Database");
}
In the end there is no comma and no issue
in the database一切都很好
现在的问题是当我把 comma in the end there is a cell created in the database with whitespace
我知道为什么会这样。包含值的分解数组的最后一个键是空格。但我想省略或留下那个空钥匙。我该怎么做?
您应该使用 array_filter()
,这将从数组中删除所有空键。所以这里是你应该使用的代码:
$categories = array_filter(explode(",",$request->get('categories')));
public function store(Request $request)
{
$article = Article::create($request->only(['content']));
$categories = explode(",",$request->get('categories'));
$category_ids =[];
foreach ($categories as $category) {
$category_db = Category::where('name', trim($category))->firstOrCreate(['name'=> trim($category)]);
$category_ids [] = $category_db->id;
}
$article->category()->attach($category_ids);
return response("Successfully Added to Database");
}
In the end there is no comma and no issue in the database一切都很好
现在的问题是当我把 comma in the end there is a cell created in the database with whitespace
我知道为什么会这样。包含值的分解数组的最后一个键是空格。但我想省略或留下那个空钥匙。我该怎么做?
您应该使用 array_filter()
,这将从数组中删除所有空键。所以这里是你应该使用的代码:
$categories = array_filter(explode(",",$request->get('categories')));