useless-stuff
2/16/2016 - 2:28 PM

PHP - RecursiveCachingIterator

PHP - RecursiveCachingIterator

<?php
/**
 * Class User
 */
class User
{

    public $name;

    /**
     * User constructor.
     * @param $name
     */
    public function __construct($name)
    {

        $this->name = $name;
    }

    /**
     * @return string
     */
    public function __toString()
    {

        return (string)$this->name;
    }
}

$data = array(
    'developers' => array(
        new User('David'),
        new User('Diego'),
        new User('John'),
    ),
    'customer_care' => array(
        new User('Samantha'),
        new User('Luisa'),
        new User('Giovanni'),
    ),
);

$iterator = new RecursiveCachingIterator(new RecursiveArrayIterator($data));
for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
    for ($iterator->getChildren()->rewind(); $iterator->getChildren()->valid(); $iterator->getChildren()->next()) {
        echo $iterator->getChildren().PHP_EOL;
    }
}

// Output:
/*
  David
  Diego
  John
  Samantha
  Luisa
  Giovanni
*/