title: How can I rearrange array items moving dependencies on top?
body: <p>I have the following <code>array</code> where each item may (or may not depend) on another one:</p>
  
  
  
  <pre class="lang-php prettyprint-override"><code>$test = array(
      'c' =&gt; array(
          'depends' =&gt; 'b'
      ),
      'a' =&gt; array(),
      'b' =&gt; array(
          'depends' =&gt; 'a'
      ),
      'd' =&gt; array(
          'depends' =&gt; 'a'
      ),
  );
  </code></pre>
  
  <p>I want to move (or make another <code>array</code>) with <strong>dependencies are moved at the top</strong>. First <code>a</code>, then <code>b</code> and <code>d</code> (both depend on <code>a</code>) and finally <code>c</code> which depends on <code>b</code>. The order of <code>b</code> and <code>d</code> is irrelevant:</p>
  
  <pre class="lang-php prettyprint-override"><code>$rearranged = array(
      'a' =&gt; array(),
      'b' =&gt; array(
          'depends' =&gt; 'a'
      ),
      'd' =&gt; array(
          'depends' =&gt; 'a'
      ),
      'c' =&gt; array(
          'depends' =&gt; 'b'
      ),
  );
  </code></pre>
  
  <p>I'm pretty sure that this is a quite common situation and before <strong>reinventing the wheel</strong> and waste time I'd like to know if there is any data structure that can do the job for me.</p>
  
  <p><strong>EDIT</strong>: forgot to say that circular references should be detected (<code>b</code> depends on <code>a</code> that depends on <code>b</code> should not be allowed).</p>