排序数组每个记录都不应重复,直到它有多个不同的值。剩余值可以随时重复

时间:2014-12-13 14:29:57

标签: php arrays

我有一个像这样的数组,并希望对它进行排序,以便重复记录,直到它有多个distinc值。

 Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 2
[6] => 2
[7] => 2
[8] => 4
[9] => 4
)

我想要这样的结果数组。

 Array
(
[0] => 1
[1] => 2
[2] => 4
[3] => 1
[4] => 2
[5] => 4
[6] => 1
[7] => 2
[8] => 1
[9] => 1
)

提前致谢..

1 个答案:

答案 0 :(得分:0)

这应该适合你:

<?php
$array = array (
    0 => 1,
    1 => 1,
    2 => 1,
    3 => 1,
    4 => 1,
    5 => 2,
    6 => 2,
    7 => 2,
    8 => 4,
    9 => 4,
);

$newArray = array();
$i = 0;

while (count($array) > 0) {

    $newArray[$i] = array();
    
    foreach ($array as $key => $value) {

        if (!in_array($value, $newArray[$i])) {
            array_push($newArray[$i], $value);
            unset($array[$key]);
        }
    }
    sort($newArray[$i]);
    $i++;
}

$index = 0;
for ($j = 0; $j < count($newArray); $j++) {
    
    foreach ($newArray[$j] as $value) {
        $array[$index] = $value;
        $index++;
    }
}
?>