我需要在 Laravel 5.3 中使用collect,但我需要帮助。
例如:
$collection = collect([
'Apple' => [
['name' => 'iPhone 6S', 'price' => '200'],
['name' => 'iPhone 7S', 'price' => '250'],
],
'Samsung' => [
['name' => 'Galaxy S7', 'price' => '300']
['name' => 'Galaxy note', 'price' => '150']
],
]);
- 如何通过 Collect 获取
Apple
或Samsung
名称?我需要获得品牌名称。 - 如何获得(名称和价格)每个品牌的最便宜价格。
谢谢你:-)
最佳答案
您可以通过mapWithKeys实现这一点
/* First get the minimum price */
$min = $collection->flatten(1)->pluck('price')->min();
/* Then perform the filteration */
$final = $collection->mapWithKeys(function($value, $key) use ($min) {
$result = collect($value)->filter(function($inner) use ($min){
return $inner['price'] === $min;
})->keys()->first();
return $result ? [$key => $value[$result]]: [];
});
当你运行上面的代码时,你会得到
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[Samsung] => Array
(
[name] => Galaxy note
[price] => 150
)
)
)
现在只需简单地获得品牌名称即可
$final->keys()->first() // Samsung
获取型号名称
$final->pluck('name')->first() // Galaxy note
关于laravel - 如何在 Laravel 5.3 中使用collect?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42374883/