Skip to content

Instantly share code, notes, and snippets.

@sword-jin
Last active September 7, 2015 14:26
Show Gist options
  • Select an option

  • Save sword-jin/a9425be8105a40fc83a7 to your computer and use it in GitHub Desktop.

Select an option

Save sword-jin/a9425be8105a40fc83a7 to your computer and use it in GitHub Desktop.
Array Iterator
<?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 />";
}
<?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