如何在Laravel 5.3中使用collect?

How to use collect in Laravel 5.3?

我需要在 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']
  ],
]);
  1. 如何通过收集获取AppleSamsung名称?我需要获得品牌名称。
  2. 如何获取(名称和价格)每个品牌最便宜的价格。

谢谢 :-)

您需要使用 each 遍历外部数组,并在内部数组中使用 min 以获得最低价格。然后您必须搜索以找到索引并返回并使用它来获取 name/price。按照这个速度,您最好编写自己的函数,这样读起来更漂亮。

$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'];
});

你可能必须收集内部项目,因为我不记得收集是否自动嵌套所有集合

你可以通过 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