Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Example usage of <a href="http://php.net/manual/class.recursivearrayiterator.php" rel="nofollow">RecursiveArrayIterator</a></p> <pre><code>$array = array( 0 =&gt; 'a', 1 =&gt; array('subA','subB',array(0 =&gt; 'subsubA', 1 =&gt; 'subsubB', 2 =&gt; array(0 =&gt; 'deepA', 1 =&gt; 'deepB'))), 2 =&gt; 'b', 3 =&gt; array('subA','subB','subC'), 4 =&gt; 'c' ); foreach (return new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key =&gt; $val) { printf( '%s: %s' . "\n", $key, $val ); } /* Output: 0: a 0: subA 1: subB 0: subsubA 1: subsubB 0: deepA 1: deepB 2: b 0: subA 1: subB 2: subC 4: c */ </code></pre> <hr> <p>extending <code>RecursiveIteratorIterator</code> to return the current key-stack</p> <pre><code>class MyRecursiveIteratorIterator extends RecursiveIteratorIterator { public function key() { return json_encode($this-&gt;getKeyStack()); } public function getKeyStack() { $result = array(); for ($depth = 0, $lim = $this-&gt;getDepth(); $depth &lt; $lim; $depth += 1) { $result[] = $this-&gt;getSubIterator($depth)-&gt;key(); } $result[] = parent::key(); return $result; } } foreach ($it = new MyRecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key =&gt; $val) { printf('%s (%s): %s' . "\n", implode('.', $it-&gt;getKeyStack()), $key, $val); } /* Output: 0 ([0]): a 1.0 ([1,0]): subA 1.1 ([1,1]): subB 1.2.0 ([1,2,0]): subsubA 1.2.1 ([1,2,1]): subsubB 1.2.2.0 ([1,2,2,0]): deepA 1.2.2.1 ([1,2,2,1]): deepB 2 ([2]): b 3.0 ([3,0]): subA 3.1 ([3,1]): subB 3.2 ([3,2]): subC 4 ([4]): c */ </code></pre> <hr> <p>Yet another version, using no RecursiveArrayIterator this time:</p> <pre><code>function flatten(array $array = array(), $keyStack = array(), $result = array()) { foreach ($array as $key =&gt; $value) { $keyStack[] = $key; if (is_array($value)) { $result = flatten($value, $keyStack, $result); } else { $result[] = array( 'keys' =&gt; $keyStack, 'value' =&gt; $value ); } array_pop($keyStack); } return $result; } foreach (flatten($array) as $element) { printf( '%s: %s (depth: %s)' . "\n", implode('.', $element['keys']), $element['value'], sizeof($element['keys']) ); } /* 0: a (depth: 1) 1.0: subA (depth: 2) 1.1: subB (depth: 2) 1.2.0: subsubA (depth: 3) 1.2.1: subsubB (depth: 3) 1.2.2.0: deepA (depth: 4) 1.2.2.1: deepB (depth: 4) 2: b (depth: 1) 3.0: subA (depth: 2) 3.1: subB (depth: 2) 3.2: subC (depth: 2) 4: c (depth: 1) */ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload