Note that there are some explanatory texts on larger screens.

plurals
  1. POFlatten Array: Keep index, value equal to position in array
    text
    copied!<p>I've been having a little trouble trying to flatten arrays in a specific way.</p> <p>Here is a <code>print_r</code> view of the array I want to flatten:</p> <pre><code>Array ( [1] =&gt; Array ( [8] =&gt; 1 [9] =&gt; 2 [10] =&gt; Array ( [15] =&gt; Array ( [22] =&gt; 1 ) [21] =&gt; 2 ) [11] =&gt; Array ( [16] =&gt; Array ( [23] =&gt; 1 ) ) ) [2] =&gt; Array ( [12] =&gt; 1 ) [3] =&gt; Array ( [13] =&gt; 1 ) [4] =&gt; Array ( [14] =&gt; 1 ) [5] =&gt; 5 [6] =&gt; 6 [7] =&gt; 7 ) </code></pre> <p>What I'm attempting to create is an array which keeps the above indexes, but the value is equal to it's position in the array, much like the original index (starting from zero). </p> <p>Here is the desired result:</p> <pre><code>Array ( [1] =&gt; 1 [2] =&gt; 2 [3] =&gt; 3 [4] =&gt; 4 [5] =&gt; 5 [6] =&gt; 6 [7] =&gt; 7 [8] =&gt; 1 [9] =&gt; 2 [10] =&gt; 3 [11] =&gt; 4 [12] =&gt; 1 [13] =&gt; 1 [14] =&gt; 1 [15] =&gt; 1 [16] =&gt; 1 [21] =&gt; 2 [22] =&gt; 2 [23] =&gt; 1 ) </code></pre> <p>Knowingly, 17 to 20 are missing.</p> <p>My function is as follows:</p> <pre><code>function array_flatten ($array) { $result = array (); $count = 1; while ($index = current($array)) { $result[key($array)] = $count; if (is_array($index)) { $result = array_merge(array_flatten($index), $result); } next($array); $count++; } return $result; } </code></pre> <p>The line <code>$result = array_merge(array_flatten($index), $result);</code> appears to be the problems. It returns:</p> <pre><code>Array ( [1] =&gt; 1 [2] =&gt; 2 [3] =&gt; 3 [4] =&gt; 4 [5] =&gt; 5 [6] =&gt; 6 [7] =&gt; 7 ) </code></pre> <p>However, if I run <code>var_dump(array_flatten($index));</code> on the same line, it returns all the arrays I wish to merge to the <code>$result</code> variable.</p> <pre><code>array 22 =&gt; int 1 array 15 =&gt; int 1 21 =&gt; int 2 array 23 =&gt; int 1 array 16 =&gt; int 1 array 8 =&gt; int 1 9 =&gt; int 2 10 =&gt; int 3 11 =&gt; int 4 array 12 =&gt; int 1 array 13 =&gt; int 1 array 14 =&gt; int 1 </code></pre> <p>It seems that that <code>array_merge</code> doesn't actually merge these arrays.</p> <p>Is there something I am doing wrong? Any words of guidance are very much appreciated. Thank you.</p> <p><em>Update</em></p> <p>Solved!</p> <p>The function which does the required is as follows:</p> <pre><code>function array_flatten($array, &amp;$result = array()) { $count = 1; foreach($array as $index =&gt; $value) { $result[$index] = $count; if(is_array($value)) { array_flatten($value, $result); } $count++; } return $result; } </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