title: PHP sort array by priority
body: <p>I need a method that sorts an array of items by priority.</p>
  
  <p>Here is what I have working so far:</p>
  
  <pre><code>function arraySortPriority(array &amp;$array, $offset, array $priorities)
  {
      uasort($array, function ($a, $b) use ($offset, $priorities) {
          if (!isset($a[$offset])) {
              $a[$offset] = null;
          }
          if (!isset($b[$offset])) {
              $b[$offset] = null;
          }
          if ($a[$offset] == $b[$offset]) {
              return 0;
          }
          $aPriority = isset($priorities[$a[$offset]])
              ? $priorities[$a[$offset]]
              : null;
          $bPriority = isset($priorities[$b[$offset]])
              ? $priorities[$b[$offset]]
              : null;
          return $aPriority &gt; $bPriority ? -1 : 1;
      });
  }
  
  // an array to sort
  $array = [
      ['type' =&gt; 'A'],
      ['type' =&gt; 'A'],
      ['type' =&gt; 'B'],
      ['type' =&gt; 'B'],
      ['type' =&gt; 'C'],
      ['type' =&gt; 'C'],
      ['type' =&gt; 'D'],
      ['type' =&gt; 'D'],
      ['type' =&gt; 'E'],
      ['type' =&gt; 'E'],
      ['type' =&gt; 'F'],
      ['type' =&gt; 'F'],
      ['type' =&gt; 'G'],
      ['type' =&gt; 'G'],
      ['type' =&gt; 'H'],
      ['type' =&gt; 'H'],
      ['type' =&gt; 'Foo'],
      ['type' =&gt; 'Foo'],
      ['type' =&gt; 'Bar'],
      ['type' =&gt; 'Bar'],
      [0 =&gt; 'no type should be last'],
      [0 =&gt; 'no type should be last'],
  ];
  // shuffle the array
  shuffle($array);
  // set priorities
  $priorities = [
      'A' =&gt; 8,
      'B' =&gt; 7,
      'C' =&gt; 6,
      'D' =&gt; 5,
      'E' =&gt; 4,
      'F' =&gt; 3,
      'G' =&gt; 2,
      'H' =&gt; 1,
  ];
  // call
  arraySortPriority($array, 'type', $priorities);
  // test output
  foreach ($array as $item) {
      if (isset($item['type'])) {
          echo "{$item['type']}\r\n";
      } else {
          $values = array_values($item);
          echo reset($values) . PHP_EOL;
      }
  }
  </code></pre>
  
  <p><strong>Expected:</strong></p>
  
  <pre><code>A
  A
  B
  B
  C
  C
  D
  D
  E
  E
  F
  F
  G
  G
  H
  H
  Foo
  Foo
  Bar
  Bar
  no type should be last
  no type should be last
  </code></pre>
  
  <p><strong>Actual:</strong></p>
  
  <pre><code>A
  A
  B
  B
  C
  C
  D
  D
  E
  E
  F
  F
  G
  G
  H
  H
  no type should be last   &lt;-- should be at bottom
  no type should be last   &lt;-- should be at bottom
  Bar
  Bar
  Foo
  Foo
  </code></pre>
  
  <p>The problem is that the items that have not been given an <code>$offset</code> should be always sorted to the bottom.</p>
  
  <p>This means that <code>no type should be last</code> should always be sorted lower than <code>Foo</code> or <code>Bar</code>.</p>
  
  <p>How can I do this?</p>