Guest User

Untitled

a guest
Dec 15th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. class ContentIterator extends RecursiveIteratorIterator
  2. {
  3. private $_ordinal = 0;
  4.  
  5. public function __construct()
  6. {
  7. parent::__construct(new RecursiveArrayIterator(func_get_args()));
  8. }
  9.  
  10. public function key()
  11. {
  12. return $this->_ordinal;
  13. }
  14.  
  15. public function getChildren()
  16. {
  17. $current = $this->current();
  18. if (property_exists($current,'array')) return new RecursiveArrayIterator(array_values($current->array()));
  19. throw new Exception('Shouldn't reach here!');
  20. }
  21.  
  22. public function hasChildren()
  23. {
  24. $current = $this->current();
  25. return is_array($current) || $current instanceof Traversable;
  26. }
  27.  
  28. public function next()
  29. {
  30. parent::next();
  31. ++$this->_ordinal;
  32. }
  33.  
  34. public function rewind()
  35. {
  36. parent::rewind();
  37. $this->_ordinal = 0;
  38. }
  39.  
  40. }
  41.  
  42. class TestSource {
  43. public $array = ['a','b','c'];
  44. }
  45.  
  46. foreach (new ContentIterator(new TestSource) as $key => $value)
  47. echo "$key => ".json_encode($value)."n";
  48.  
  49. 0 => "a"
  50. 1 => "b"
  51. 2 => "c"
  52.  
  53. 0 => ["a","b","c"]
Add Comment
Please, Sign In to add comment