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
convert null values into empty string in laravel 5.4
提问by
I want to convert all null with empty string I have used array_walk_recursive
but 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_recursive
so 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_recursive
will 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);
$output
contains the result you wanted. You can return
it or do whatever you want to do with it.
$output
包含您想要的结果。您可以使用return
它或做任何您想做的事情。
Note:you can instead use array_walk()
if $input
not an associative array.
注意:array_walk()
如果$input
不是关联数组,您可以改为使用。