php - 对可翻译的 json 列进行排序
问题描述
我在 laravel 中使用 spatie 翻译包。我有我想按名称排序的集合,但名称列有一个 json 集合,因此它没有被排序。我试过了
$shoptype->categories->sortBy('name.en');
和我的结果
{
"id": 8,
"type_id": 1,
"name": "{\"en\":\"Other Meats\",\"es\":\"Otras Carnes\"}",
"image_path": "http://market.test/uploads/category/Cpaf7nCVZxshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-08-14T06:17:35.000000Z",
"deleted_at": null
},
{
"id": 9,
"type_id": 1,
"name": "{\"en\":\"Turkey\",\"es\":\"Pavo\"}",
"image_path": "http://market.test/uploads/category/8U2qP2mrzashoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:01.000000Z",
"deleted_at": null
},
{
"id": 10,
"type_id": 1,
"name": "{\"en\":\"Chicken\",\"es\":\"Pollo\"}",
"image_path": "http://market.test/uploads/category/SnP7mwnTeBshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:14.000000Z",
"deleted_at": null
},
{
"id": 11,
"type_id": 1,
"name": "{\"en\":\"Beef\",\"es\":\"Carne De Vaca\"}",
"image_path": "http://market.test/uploads/category/b7IKzAGUHDshoptype.png",
"created_at": "2021-04-02T12:13:14.000000Z",
"updated_at": "2021-05-26T05:48:50.000000Z",
"deleted_at": null
}```
解决方案
SortBy
与回调一起使用。
使用collect
方法转换categories
好像collection
不是
$categories = collect($shoptype->categories)->sortBy(function($category, $key){
return (json_decode( $category->name))->en;
});
if$shoptype->categories
已经是一个集合
$categories = $shoptype->categories->sortBy(function($category, $key){
return (json_decode( $category->name))->en;
});
if categories
is Json then use json_decode($shoptype->categories);
and use sortBy
withcollect
方法