Skip to content

Instantly share code, notes, and snippets.

@ichikaway
Created May 22, 2012 12:37
Show Gist options
  • Save ichikaway/2768801 to your computer and use it in GitHub Desktop.
Save ichikaway/2768801 to your computer and use it in GitHub Desktop.
RecursiveIteratorIterator example
<?php
Class TableRII extends RecursiveIteratorIterator {
private $parentKey = null;
public function beginIteration() {
echo '<table border=1><tr><th>key</th><th>value</th></tr>';
}
public function endIteration() {
echo '</table>';
}
public function beginChildren() {
echo '<tr><td>'. $this->parentKey .'</td><td><table border=1>';
}
public function endChildren() {
echo '</table></td></tr>';
}
public function callHasChildren() {
$bool = parent::callHasChildren();
if($bool) {
$this->parentKey = $this->key();
}
return $bool;
}
public function current() {
return '<tr><td>'. $this->key() .'</td><td>'. parent::current() . '</td></tr>';
}
}
/*-------main----------*/
$array = array(
array('Post' => array('id' => 1, 'title' => 'aa1')),
array('Post' => array('id' => 2, 'title' => 'aa2')),
array('Post' => array('id' => 3, 'title' => 'aa3')),
);
$Iterator = new TableRII(new RecursiveArrayIterator($array), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($Iterator as $k => $v) {
if(!is_array($v)){
echo $v. "\n";
}
}
@miquelbrazil
Copy link

I'm working on a form builder that uses JSON Schema and I've been experimenting with strategies for iterating over the JSON object. I've mainly been constructing a recursive method but kept feeling like the SPL iterators were the better way to go. The problem was that the documentation on php.net confused me too much so I kept trying to fit a square peg into a round whole (my iterator method had ballooned into an unwieldily beast trying to get it to search for specified keys and triggering callbacks, etc).

Your Gist explained the Iterator so much clearer. I now see exactly how I could use it in my project and actually easily make several iterators for different kinds of tasks.

Thank you so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment