laravel - 如何在 Laravel 5.3 中使用collect?

标签 laravel laravel-5.3 collect

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

谢谢你:-)

最佳答案

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

相关文章:

string - 根据字符串列表过滤 Scala 字符串序列

php - 使用 session 时 Laravel 的点符号出现问题

Laravel Eloquent 日期条件

php - 卸载 Laravel 代客

mysql - 从温度和 ID 数据库创建 Google Charts API 数据表

mysql - Laravel Sql 语法错误

ruby - 关于Ruby collect 方法的问题

collections - Java 8 中分组的反转

php - 如何根据 Post 请求以 Laravel 形式重定向?

Laravel 分页链接未显示?