我需要用Laravel5.3收集站,但我需要帮助。
例如:
$collection = collect([
'Apple' => [
['name' => 'iPhone 6S', 'price' => '200'],
['name' => 'iPhone 7S', 'price' => '250'],
],
'Samsung' => [
['name' => 'Galaxy S7', 'price' => '300']
['name' => 'Galaxy note', 'price' => '150']
],
]);Apple或Samsung的名称?我要知道品牌的名字。谢谢:-)
发布于 2017-02-22 03:39:35
您可以通过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发布于 2017-02-21 18:43:12
您需要使用每个数组来遍历外部数组,并在内部数组中使用min来获得最小价格。然后,您必须搜索以找到索引,然后返回并使用它来获取名称/价格。在这种情况下,最好是编写自己的函数,更好地阅读。
$collection->each(function ($item, $brand) {
$minPrice = $item->min('price');
$minIndex = $item->search(function ($item) use ($minPrice) {
return $item['price'] == $minPrice
});
echo $brand.' '.$item[$minIndex]['name']. ' '.$item[$minIndex]['price'];
});您可能不得不在内部项目上收集,因为我不记得是否收集自动嵌套所有集合
https://stackoverflow.com/questions/42374883
复制相似问题