fork download
  1. <?php
  2.  
  3. class ZipIterator implements \Iterator
  4. {
  5. const ZIP_ALL = '{6087F687-D674-4549-AFBF-8D4DC07FE06F}';
  6.  
  7. private $_iterators;
  8.  
  9. private $_zipAll = false;
  10.  
  11. public function __construct()
  12. {
  13. foreach (func_get_args() as $argument) {
  14. if ($argument === self::ZIP_ALL) {
  15. $this->_zipAll = true;
  16. }
  17. else if (is_array($argument)) {
  18. $this->_iterators[] = new \ArrayIterator($argument);
  19. }
  20. else if ($argument instanceof \Traversable) {
  21. $this->_iterators[] = $argument;
  22. }
  23. else {
  24. throw new Exception("All arguments to ".__CLASS__." must be arrays or implement Traversable.");
  25. }
  26. }
  27. }
  28.  
  29. public function current()
  30. {
  31. $result = [];
  32. foreach ($this->_iterators as $iterator) {
  33. $result[] = $iterator->current();
  34. }
  35.  
  36. return $result;
  37. }
  38.  
  39. public function next()
  40. {
  41. foreach ($this->_iterators as $iterator) {
  42. $iterator->next();
  43. }
  44. }
  45.  
  46. public function key()
  47. {
  48. $result = [];
  49. foreach ($this->_iterators as $iterator) {
  50. $result[] = $iterator->key();
  51. }
  52.  
  53. return $result;
  54. }
  55.  
  56. public function valid()
  57. {
  58. foreach ($this->_iterators as $iterator) {
  59. if ($iterator->valid() ^ !$this->_zipAll) {
  60. return $this->_zipAll;
  61. }
  62. }
  63.  
  64. return !$this->_zipAll;
  65. }
  66.  
  67. public function rewind()
  68. {
  69. foreach ($this->_iterators as $iterator) {
  70. $iterator->rewind();
  71. }
  72. }
  73. }
  74.  
  75. $a = [ 1, 2, 3 ];
  76. $b = [ 'foo', 'bar' ];
  77.  
  78. foreach (new ZipIterator($a, $b) as $pair) {
  79. echo implode(" ", $pair)."\n";
  80. }
  81.  
  82. foreach (new ZipIterator($a, $b, ZipIterator::ZIP_ALL) as $pair) {
  83. echo implode(" ", $pair)."\n";
  84. }
  85.  
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
1 foo
2 bar
1 foo
2 bar
3