title: Merge arrays at correct position while maintaining order
body: <p>I have two arrays, both have a <code>position</code>. I need to merge them together, in their correct positions, while maintaining the order of the elements in each array.</p>
  
  <pre><code>$array1 = array(
      array('name' =&gt; 'Bob', 'position' =&gt; 1),
      array('name' =&gt; 'Tim', 'position' =&gt; 1),
      array('name' =&gt; 'Alf', 'position' =&gt; 3),
      array('name' =&gt; 'Jon', 'position' =&gt; 3) 
  );
  
  $array2 = array(
      array('name' =&gt; 'Tom', 'position' =&gt; 2),
      array('name' =&gt; 'Joe', 'position' =&gt; 2),
      array('name' =&gt; 'Jim', 'position' =&gt; 2),
      array('name' =&gt; 'Kev', 'position' =&gt; 2)
  );
  </code></pre>
  
  <p>The output I would like is:</p>
  
  <pre><code>$output = array(
      array('name' =&gt; 'Bob', 'position' =&gt; 1),
      array('name' =&gt; 'Tim', 'position' =&gt; 1),
      array('name' =&gt; 'Tom', 'position' =&gt; 2),
      array('name' =&gt; 'Joe', 'position' =&gt; 2),
      array('name' =&gt; 'Jim', 'position' =&gt; 2),
      array('name' =&gt; 'Kev', 'position' =&gt; 2),
      array('name' =&gt; 'Alf', 'position' =&gt; 3),
      array('name' =&gt; 'Jon', 'position' =&gt; 3) 
  );
  </code></pre>
  
  <p>I thought the best way to do it would be to use <code>array_merge()</code>, merging the two arrays, then use a simple <code>usort()</code> to sort them based on their position. However, when I do this, the order of elements from <code>$array2</code> isn't correct:</p>
  
  <pre><code>$output = array_merge($array1, $array2);
  
  usort($output, function($a, $b) {
      return $a['position'] &gt; $b['position'];
  });
  
  var_dump($output);
  </code></pre>
  
  <p>Which outputs:</p>
  
  <pre><code>$output = array(
      array('name' =&gt; 'Bob', 'position' =&gt; 1),
      array('name' =&gt; 'Tim', 'position' =&gt; 1),
      array('name' =&gt; 'Tom', 'position' =&gt; 2),
      array('name' =&gt; 'Joe', 'position' =&gt; 2),
      array('name' =&gt; 'Kev', 'position' =&gt; 2), // Should be 'name' =&gt; 'Jim'
      array('name' =&gt; 'Jim', 'position' =&gt; 2), // Should be 'name' =&gt; 'Kev'
      array('name' =&gt; 'Alf', 'position' =&gt; 3),
      array('name' =&gt; 'Jon', 'position' =&gt; 3) 
  );
  </code></pre>
  
  <p>Is there a way to solve this problem, or a better way of doing it altogether?</p>