laravel 在laravel 5.4 中将空值转换为空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44038644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:59:42  来源:igfitidea点击:

convert null values into empty string in laravel 5.4

phplaravellaravel-5laravel-5.4

提问by

I want to convert all null with empty string I have used array_walk_recursivebut I haven't got what I want please help me to figure it out what I have done wrong here.

我想用我使用过的空字符串转换所有 null,array_walk_recursive但我没有得到我想要的东西,请帮我弄清楚我在这里做错了什么。

protected function setData($key, $value)
{
    $this->data[$key] = $value;
    array_walk_recursive($this->data, function (&$item, $key) {
        $item = null === $item ? '' : $item;
    });
    return $this->data;
}

采纳答案by

well, that's just a lamp mistake in eloquent we always get result in eloquent object and here I'm passing eloquent object inside array_walk_recursiveso before passing I need to convert into array from eloquent object using ->toArray()method in laravel like this.

好吧,这只是 eloquent 中的一个灯错误,我们总是在 eloquent 对象中得到结果,在这里我将 eloquent 对象array_walk_recursive传递给内部,所以在传递之前我需要使用->toArray()laravel 中的方法将 eloquent 对象转换为数组,就像这样。

inside User Controller

内部用户控制器

$this->setData("friendList", $loadFriends->friends->toArray());

then array_walk_recursivewill work.

然后array_walk_recursive将工作。

protected function setData($key, $value)
{
    array_walk_recursive($value, function (&$item, $key) {
        $item = null === $item ? '' : $item;
    });
    $this->data[$key] = $value;
    return $this->data;
}

回答by sampath wijesinghe

    class InputCleanup
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $input = $request->input();

        array_walk_recursive($input, function(&$value) {

            if (is_string($value)) {
                $value = StringHelper::trimNull($value);
            }
        });

        $request->replace($input);

        return $next($request);
    }
}

回答by Gayan

Your array_walk_recursive()method should be modified as follows.

您的array_walk_recursive()方法应修改如下。

array_walk_recursive($input, function($i) use (&$output) {
    $output[] = is_null($i)? '': $i;
});
var_dump($output);

$outputcontains the result you wanted. You can returnit or do whatever you want to do with it.

$output包含您想要的结果。您可以使用return它或做任何您想做的事情。

Note:you can instead use array_walk()if $inputnot an associative array.

注意:array_walk()如果$input不是关联数组,您可以改为使用。