在我的laravel请求中,我正在发送数据,如下所示。
{
"user_id":13,
"location":null,
"about":"This Is About the user",
"avatar":[],
"users":[
{
"user_name":"John",
"age":"30",
},
{
"user_name":"Jessy",
"age":"30",
}
]
}
所有的请求键都可以是空的,也可以保存一个值(数组或字符串),所以我只想过滤有值的键。
预期输出:
{
"user_id":13,
"about":"This Is About the user",
"users":[
{
"user_name":"John",
"age":"30",
},
{
"user_name":"Jessy",
"age":"30",
}
]
}
我试过了
$userRequestData = $request->only([
'location','about','avatar','users'
]);
$Data = array_filter($userRequestData, 'strlen');
但它只有在请求只有字符串值时才起作用...
我如何过滤它,即使它是一个字符串或数组?
发布于 2021-07-14 20:53:34
如果您不将'strlen'
参数传递给array_filter,它将过滤掉falsy
值:
$request = [
"user_id"=>13,
"location"=>null,
"about"=>"This Is About the user",
"avatar"=>[],
"users"=>[
[
"user_name"=>"John",
"age"=>"30",
],
[
"user_name"=>"Jessy",
"age"=>"30",
]
]
];
将会变成
$request = [
"user_id"=>13,
"about"=>"This Is About the user",
"users"=>[
[
"user_name"=>"John",
"age"=>"30",
],
[
"user_name"=>"Jessy",
"age"=>"30",
]
]
];
Documentation for array_filter
在您的示例中,您可以这样做:
$userRequestData = array_filter($userRequestData);
发布于 2021-07-14 20:50:44
您可以使用集合来过滤空值
collect(request()->all())->filter()
或
$result = collect(request()->all())->filter(function ($request){
return is_string($request)&&!empty($request)||is_array($request)&&count($request);
});
获取数组
$result=collect(request()->all())->filter()->toArray()
或自定义
$result = collect(request()->all())->filter(function ($request){
return is_string($request)&&!empty($request)||is_array($request)&&count($request);
})->toArray();
https://stackoverflow.com/questions/68378389
复制相似问题