我如何在PHP中删除包含空格的键,Laravel?

问题描述 投票:-1回答:1
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时,在database with whitespace中创建了一个单元格

我知道为什么会这样。包含值的分解数组的最后一个键是空格。但是我想省略或留下那个空键。我该怎么办?

php arrays laravel trim explode
1个回答
0
投票

您应使用array_filter(),它将从阵列中删除所有空键。所以这是您应该使用的代码:

$categories = array_filter(explode(",",$request->get('categories')));
© www.soinside.com 2019 - 2024. All rights reserved.