Sorting an array with repeating values and retaining the index order after value sort
<p>I'm not sure why I'm having a problem with this but I'm trying to sort an array such as "0,1,0,0,1,1,0,0" so that the number 1's appear at the end, but the array indexes are retained as per their original order.</p>

<p>With the following code example</p>

<pre><code>&lt;pre&gt;&lt;?php
  $array = array(0,1,0,0,1,1,0,0);
  print_r($array);
  asort($array);
  print_r($array);
?&gt;&lt;/pre&gt;
</code></pre>

<p>Starting with the original array:</p>

<pre><code>Array
(
    [0] =&gt; 0
    [1] =&gt; 1
    [2] =&gt; 0
    [3] =&gt; 0
    [4] =&gt; 1
    [5] =&gt; 1
    [6] =&gt; 0
    [7] =&gt; 0
)
</code></pre>

<p>After performing the asort($array):</p>

<pre><code>Array
(
    [6] =&gt; 0
    [7] =&gt; 0
    [0] =&gt; 0
    [3] =&gt; 0
    [2] =&gt; 0
    [1] =&gt; 1
    [5] =&gt; 1
    [4] =&gt; 1
)
</code></pre>

<p>But what do I need to do so I can have the following output? (Note index order)</p>

<pre><code>Array
(
    [0] =&gt; 0
    [2] =&gt; 0
    [3] =&gt; 0
    [6] =&gt; 0
    [7] =&gt; 0
    [1] =&gt; 1
    [4] =&gt; 1
    [5] =&gt; 1
)
</code></pre>

<p>I'd realy like to avoid having to do further processing loops to reorder the indexes by distinct value groups (ie sort all the indexes on the items with value "0" then items with value "1" and merge the results)</p>

<hr>

<p>Edit: this is really messy, but solves what I want to achieve as an example</p>

<pre><code>print_r(stupid_array_order_hack($array));
function stupid_array_order_hack($array) {
  if(isset($array) === TRUE AND is_array($array) === TRUE) {
    $reordering_group = array();
    $reordering_merge = array();
    // Group the index's by value
    foreach($array as $key =&gt; $value) {
      $reordering_group[$value][] = $key;
    }
    // sort the grouped index's
    foreach($reordering_group as $key =&gt; $value) {
      asort($reordering_group[$key]);
      $reordering_merge = array_merge($reordering_merge,$reordering_group[$key]);
    }
    return array_replace(array_flip($reordering_merge),$array);
  }
  return $array;
}
</code></pre>

<hr>

<p><strong>Solution:</strong> Method using array_multisort()</p>

<pre><code>$array = array(0,1,0,0,1,1,0,0);
$temp = array($array,array_keys($array));
array_multisort($temp[0],SORT_ASC,$temp[1],SORT_ASC);
$array = array_combine($temp[1], $temp[0]);
</code></pre>
