Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP interesting recursion with element's removing
    text
    copied!<p><br>I have a multidimensional array. And some of array's elements have 'inactive' flag. I need to remove this elements. But downline elements should be go up. I wrote a function, but it works wrong. It works fine only if first array element is inactive. <br>Function:</p> <pre><code>function deleteInactive($children, $generation = 0) { $generation++; $copy = $children; if (!empty($copy) &amp;&amp; is_array($copy)) { foreach ($copy as $key =&gt; $v) { $inactive = false; if (array_key_exists('inactive', $v) &amp;&amp; $v['inactive'] === true) { $nextGeneration = $generation - 1; $inactive = true; $children = deleteInactive($v['children'], $nextGeneration); unset($children[$key]); } else { $nextGeneration = $generation; if (!empty($v['children']) &amp;&amp; is_array($v['children'])) { $children[$key] = $v; $children[$key]['children'] = deleteInactive($v['children'], $generation); } } if (!$inactive) { $children[$key]['generation'] = $nextGeneration; } } } return $children; } </code></pre> <p>Test array:</p> <pre><code>$tree = array( 'id' =&gt; 1000, 'generation' =&gt; 0, 'children' =&gt; array( 1002 =&gt; array( 'id' =&gt; 1002, 'generation' =&gt; 1, 'children' =&gt; array( 1005 =&gt; array( 'id' =&gt; 1005, 'generation' =&gt; 2, 'inactive' =&gt; true, 'children' =&gt; array() ) ) ), 1006 =&gt; array( 'id' =&gt; 1006, 'generation' =&gt; 1, 'inactive' =&gt; true, 'children' =&gt; array( 1007 =&gt; array( 'id' =&gt; 1007, 'generation' =&gt; 2, 'children' =&gt; array() ) ) ), 1008 =&gt; array( 'id' =&gt; 1008, 'generation' =&gt; 1, 'children' =&gt; array( 1009 =&gt; array( 'id' =&gt; 1009, 'generation' =&gt; 2, 'children' =&gt; array() ) ) ) ) ); </code></pre> <p>Testing:</p> <pre><code>print_r($tree); $tree['children'] = deleteInactive($tree['children']); print_r($tree); </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