用 collection 重构代码

安装

composer require illuminate/support

Laravel 框架已经自带此组件

引用

require 'vendor/autoload.php';

map

$array = [];
$collection = collect($array)->map(function($item) {
  return $item;
});

sum

// 基本求和
collect([])->sum('price');

相当于

$price = 0;
foreach($products as $product) {
  $price += $product['price'];
}
// 高级求和(单价×数量)
collect([])->groupBy('date')->map(function($item) {
  return $item->sum(function($item) {
    return ($item['price'] * $item['qty']);
  });
});

flatten

$arr = [
  [1, 2],
  [3, 4]
];
collect($arr)->flatten(1);
// 输出
[ 1, 2, 3, 4 ]

pluck

collect([])->pluck('type');

相当于

collect([])->map(function($item) {
  return $item['type'];
});

get

$arr = ['a'=>2, 'b'=>3, 'c'=>4];
collect($arr)->get('b'); // 返回 3
collect($arr)->get('d', 1); // 返回 1

implode

$string = collect([])->map(function($item){
  return $item;
})->implode("\n");

相当于

$string = '';
foreach([] as $item) {
  $string .= $item . "\n";
}
$string = substr($string, 0, -1);

zip

$arr1 = [100, 200, 300];
$arr2 = [1000, 2000, 3000];
$arr3 = collect($arr1)->zip($arr2);
// 输出 $arr3
Collection {
  [
    Collection {
      [100, 1000]
    }
  ],
  [
    Collection {
      [200, 2000]
    }
  ],
  [
    Collection {
      [300, 3000]
    }
  ]
}

$arr3->map(function($item) { // $item = 0, 1, 2
  return $item->first() - $item->last();
});

reduce

参照 php 原生 array_reduce

collect([])->reduce(function($lookup, $item) {
  $lookup[$item['key']] = $item['value'];
  return $lookup;
}, []);

groupBy

$arr = [
  [
    'date' => '2015-12-25',
    'name' => 'Jerry'
  ],
  [
    'date' => '2015-12-25',
    'name' => 'Andy'
  ],
  [
    'date' => '2016-10-12',
    'name' => 'Jerry'
  ]
];
collect($arr)->groupBy('date');
// 输出
Collection {
  [
    '2015-12-25' => Collection {
      [
        [
          'date' => '2015-12-25',
          'name' => 'Jerry'
        ],
        [
          'date' => '2015-12-25',
          'name' => 'Andy'
        ]
      ]
    },
    '2016-10-12' => Collection {
      [
        [
          'date' => '2016-10-12',
          'name' => 'Jerry'
        ]
      ]
    }
  ]
}

unique

合并重复项

collect(['a','a','b','b'])->unique(function($item){
    return $item;
});
// 输出
Collection {
    ['a', 'b']
}