【问题标题】:How to use collect in Laravel 5.3?如何在 Laravel 5.3 中使用收集?
【发布时间】:2017-02-21 18:13:12
【问题描述】:

我需要在 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. 如何获得(名称和价格)每个品牌的最便宜的价格。

谢谢你:-)

【问题讨论】:

  • 您参考了文档吗?
  • 嗨@curious_coder ,是的,但是对于我的问题,我没有找到答案!
  • 你能展示你想要的输出吗?

标签: laravel laravel-5.3 collect


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您需要使用 each 来遍历外部数组并使用内部数组中的 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'];
    });
    

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

    【讨论】:

      猜你喜欢
      • 2017-06-28
      • 2017-02-28
      • 1970-01-01
      • 2017-01-25
      • 2019-06-14
      • 2017-03-19
      • 2017-01-25
      • 1970-01-01
      相关资源
      最近更新 更多