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.
With the following code example
<pre><?php
$array = array(0,1,0,0,1,1,0,0);
print_r($array);
asort($array);
print_r($array);
?></pre>
Starting with the original array:
Array
(
[0] => 0
[1] => 1
[2] => 0
[3] => 0
[4] => 1
[5] => 1
[6] => 0
[7] => 0
)
After performing the asort($array):
Array
(
[6] => 0
[7] => 0
[0] => 0
[3] => 0
[2] => 0
[1] => 1
[5] => 1
[4] => 1
)
But what do I need to do so I can have the following output? (Note index order)
Array
(
[0] => 0
[2] => 0
[3] => 0
[6] => 0
[7] => 0
[1] => 1
[4] => 1
[5] => 1
)
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)
Edit: this is really messy, but solves what I want to achieve as an example
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 => $value) {
$reordering_group[$value][] = $key;
}
// sort the grouped index's
foreach($reordering_group as $key => $value) {
asort($reordering_group[$key]);
$reordering_merge = array_merge($reordering_merge,$reordering_group[$key]);
}
return array_replace(array_flip($reordering_merge),$array);
}
return $array;
}
Solution: Method using array_multisort()
$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]);