我正在尝试使用集合filter()方法来过滤以下集合:
$collection = Word::all();
其中JSON输出如下所示:
[
{
"id": "1",
"word": "dog",
"phonetic": "dog",
"mean": "pies",
"assoc": "some example text",
"author_id": "3",
"user_id": "3"
},
{
"id": "2",
"word": "sun",
"phonetic": "sun",
"mean": "słońce",
"assoc": "lorem ipsun dolor sit amet",
"author_id": "3",
"user_id": "2"
}, ...
]
但是,当过滤集合时:
$filtered_collection = $collection->filter(function($item)
{
if($item->isDog())
{
return $item;
}
});
过滤后的集合JSON输出将如下所示:
{"1":
{
"id": "1",
"word": "dog",
"phonetic": "dog",
"mean": "pies",
"assoc": "some example text",
"author_id": "3",
"user_id": "3"
},
"2":
{
"id": "2",
"word": "sun",
"phonetic": "sun",
"mean": "słońce",
"assoc": "lorem ipsun dolor sit amet",
"author_id": "3",
"user_id": "2"
}}
[在过滤集合时如何保留原始JSON输出?过滤原始集合时,我想拥有一个Eloquent模型实例的数组。在此先感谢:)
集合的filter
方法在基础数组上调用array_filter
,该数组according to the PHP docs保留数组键。然后,这会将您的数组转换为JavaScript对象而不是数组。
在您的集合上调用values()
以重置基础数组上的键:
$filtered_collection = $collection->filter(function ($item) {
return $item->isDog();
})->values();
只需记住Laravel documentation的说明,将其转换为JSON:
注:在过滤集合并将其转换为JSON时,请尝试首先调用values函数以重置数组的键。
所以最终的代码将是:
$filtered_collection->values()->toJson();
也可以用这种方法从数据库中过滤。
//request the form value
$name=$request->name;
$age=$request->age;
$number=$request->phone;
//write a query to filter
$filter_result = DB::table('table_name')
->where('name', 'like', '%'.$name.'%')
->orWhere('age', 'like', '%'.$age.'%')
->orWhere('phone', 'like', '%'.$number.'%')
->get();
if(is_null($filter_result)){
return redirect()->back()->with('message',"No Data Found");
}else{
return view('resultpage',compact('filter_result'));
}