Last active
September 7, 2015 14:26
-
-
Save sword-jin/a9425be8105a40fc83a7 to your computer and use it in GitHub Desktop.
Array Iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class AuthorFilter extends FilterIterator | |
| { | |
| /** | |
| * @var Iterator | |
| */ | |
| private $author; | |
| public function __construct(Iterator $iterator, $author) | |
| { | |
| parent::__construct($iterator); | |
| $this->author = $author; | |
| } | |
| public function accept() | |
| { | |
| return $this->current()->author == $this->author; | |
| } | |
| } | |
| $courses = file_get_contents('common/data/courses.json'); | |
| $courses = json_decode($courses); | |
| $courses = new ArrayIterator($courses); | |
| $courses = new AuthorFilter($courses, 'David Powers'); | |
| foreach ($courses as $course) { | |
| echo "$course->title author by $course->author<br />"; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $products = [ | |
| 'Person' => ['Jacak', 'Tom', 'Cakkry'], | |
| 'Animals' => ['Snack', 'Tigger', 'Lion'], | |
| 'Sport' => ['Basketball', 'Fans' => ['One', 'tow', 'three']], | |
| ]; | |
| $products = new RecursiveArrayIterator($products); | |
| $products = new RecursiveIteratorIterator($products, RecursiveIteratorIterator::SELF_FIRST); | |
| foreach ($products as $key => $value) { | |
| $level = $products->getDepth() + 2; | |
| if ($products->hasChildren()) { | |
| echo "<h$level>$key</h$level>" . '<br />'; | |
| } else { | |
| echo $value . '<br />'; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment