5 March 2015

How to get values by key name in multidimensional array. You have to iterate it recursively. This is the first time I can use Iterator classes of PHP and I already can think multiple problems this could solve. So first step into Recursive Iterators of PHP.

Source code viewer
  1. $array = array(id => 1, name => 2, children => array(id => 3));
  2. $ids = array();
  3. $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
  4. foreach ($iterator as $key => $value) {
  5. if ($key === 'id') {
  6. $ids[] = $value;
  7. }
  8. }
  9. print_r($id);
  10. // Would return array(1, 3)
Programming Language: PHP