1. <?php
  2. /**
  3. * collection
  4. */
  5. class Collection
  6. {
  7. protected $items;
  8. public function __construct(array $items)
  9. {
  10. $this->items = $items;
  11. }
  12. public function make($items)
  13. {
  14. return new static($items);
  15. }
  16. public function map($transform)
  17. {
  18. return new static(array_map($transform, $this->items));
  19. }
  20. public function filter($criteria)
  21. {
  22. return new static(array_filter($criteria, $this->items));
  23. }
  24. }
  25. $hellos = [
  26. [
  27. 'title' => 'hello',
  28. 'content' => 'this is hello world!',
  29. ],
  30. [
  31. 'title' => 'hello2',
  32. 'content' => 'this is hello2 world!',
  33. ],
  34. [
  35. 'title' => 'hello3',
  36. 'content' => 'this is hello3 world!',
  37. ],
  38. ];
  39. $titleCollection = Collection::make($hellos)->map(
  40. function ($episode) {
  41. return $episode['title'];
  42. });
  43. var_dump($titleCollection);

参考:https://boxueio.com/series/do-not-loop-again/ebook/114

分类: web

标签: