title: PHP Sorting an array based on list of values
body: <p>I'm looking for an approach to sort an array of arrays.</p>
  
  <p>Here is simplified example;</p>
  
  <pre><code>$myArray = [ 
    ['ref' =&gt; 103, 'refList' =&gt; '101,102,111'],
    ['ref' =&gt; 104, 'refList' =&gt; '101,103'],
    ['ref' =&gt; 105, 'refList' =&gt; '106,103'],
    ['ref' =&gt; 106, 'refList' =&gt; '103,104,110'],
  ];
  </code></pre>
  
  <p>The sorting rule for the array items is;</p>
  
  <blockquote>
    <p>Items with references contained in the 'refList' must come after any items with the matching 'ref'</p>
  </blockquote>
  
  <p>So in this scenario the correct order would be;</p>
  
  <pre><code>  ['ref' =&gt; 103, 'refList' =&gt; '101,102,111'],
    ['ref' =&gt; 104, 'refList' =&gt; '101,103'],
    ['ref' =&gt; 106, 'refList' =&gt; '103,104'],
    ['ref' =&gt; 105, 'refList' =&gt; '106,103,110'],
  </code></pre>
  
  <p>I've tried some very long winded approaches and also usort(), but can't get this right. I went down the following route;</p>
  
  <pre><code>usort($myArray, 'refSorter');
  
  function refSorter($a, $b) {
  
      $arrayOfRefs = explode(',', $b['refList']);
  
      if (in_array($a['ref'], $arrayOfRefs)) {
          return 1;
      }
      return 0;
  }
  </code></pre>