php - 从集合中获取最高价值
问题描述
我有一系列产品,即
Collection {#567 ▼
#items: array:3 [▼
0 => Product {#571 ▼
#searchable: array:1 [▶]
#fillable: array:17 [▶]
#hidden: []
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:19 [▼
"id" => 12
"brand_id" => null
"sku" => "1002796"
"name" => "In quo vero error dolorem est."
"slug" => "in-quo-vero-error-dolorem-est"
"description" => "<p>Dicta ipsum quis soluta pariatur iure rerum quo. Voluptatibus nulla eveniet ab esse vero. Atque et quod fuga non.</p>"
"cover" => "products/W2INR8joy2tLuRLOXv4h5r51I7Vpcjq3hXemzvzI.png"
"quantity" => 10
"price" => "5.00"
"sale_price" => "10.00"
"status" => 1
"length" => null
"width" => null
"height" => null
"distance_unit" => null
"weight" => "5.00"
"mass_unit" => "lbs"
"created_at" => "2018-08-30 17:27:30"
"updated_at" => "2018-09-11 14:30:54"
]
#original: array:21 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▶]
#touches: []
+timestamps: true
#visible: []
#guarded: array:1 [▶]
#search_bindings: []
}
1 => Product {#568 ▶}
2 => Product {#569 ▶}
]}
所以我需要的是获得折扣价最高的产品。在这种情况下,折扣价是 price - sale_price。到目前为止,我尝试从集合中循环这些项目,并尝试了一些收集方法,如过滤、减少,以获取哪些产品的折扣价最高,但我未能成功。可能是我做错了什么,或者我完全错过了一部分。
感谢任何愿意帮助我的人。:)
解决方案
使用sortByDesc()
:
$max = $products->sortByDesc(function($product) {
return $product->price - $product->sale_price;
})->first();
推荐阅读
- python - 递归函数二进制转十进制
- python - 如何在python中重复找到每个T数字的数字之和的数字之和,直到它成为一个数字?
- python - Shape of the input layer
- visual-studio - Visual Studio 中的 MSBuild 项目
- flutter - Flutter - 检测内存泄漏
- angular - 在 Angular 6 Card Botton-Center 边框上添加图像/徽章
- asp.net-core - ASP.NET Core Identity - NormalizedUserName, NormalizedEmail
- vba - Generate "n" random numbers between a and b to reach desired average in m rows
- gcc - gcc 8.2:错误:无效的“asm”:无效的地址模式
- python - Understanding Python Pandas dataframes