【问题标题】:How can i remove the key which contain the value white space in PHP, Laravel?如何删除包含 PHP、Laravel 中值空格的键?
【发布时间】:2020-07-29 08:25:54
【问题描述】:
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 中创建了一个单元格

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

【问题讨论】:

  • if ('' == trim($category)) SKIP

标签: php arrays laravel trim explode


【解决方案1】:

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

$categories = array_filter(explode(",",$request->get('categories')));

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2014-01-01
    • 2019-06-01
    相关资源
    最近更新 更多