Ker*_*nes 7 php arrays sorting algorithm
这样做有什么好的或标准的方法吗?
请看以下示例:
$values = array(
'blue'
, 'blue'
, 'blue'
, 'blue'
, 'green'
, 'red'
, 'yellow'
, 'yellow'
, 'purple'
, 'purple'
, 'purple'
);
Run Code Online (Sandbox Code Playgroud)
我需要它被分开,所以没有两个相同的值接触(除非没有可能的解决方案 - 在这种情况下,要么生成错误,返回false或其他任何东西都是可接受的).
这是上面的数组(手工完成),但我是如何尝试更改它的:
$values = array(
'blue'
, 'purple'
, 'green'
, 'purple'
, 'blue'
, 'red'
, 'blue'
, 'yellow'
, 'blue'
, 'yellow'
, 'purple'
)
Run Code Online (Sandbox Code Playgroud)
这些价值在开始时不一定是有序的 - 这只是为了简单起见.
有任何想法吗?任何让我开始正确方向的代码?
这个函数应该可以解决问题:
function uniq_sort($arr){
if(!count($arr))
return array();
$counts = array_count_values($arr);
arsort($counts);
while(NULL !== ($key = key($counts)) && $counts[$key]){
if(isset($prev) && $prev == $key){
next($counts);
$key = key($counts);
if($key === NULL)
return false;
}
$prev = $result[] = $key;
$counts[$key]--;
if(!$counts[$key])
unset($counts[$key]);
arsort($counts);
reset($counts);
}
return $result;
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
$values = array('blue', 'blue', 'blue', 'blue', 'green', 'red', 'yellow', 'yellow', 'purple', 'purple', 'purple');
print_r(uniq_sort($values));
$values = array('a', 'b', 'b');
print_r(uniq_sort($values));
$values = array(1);
print_r(uniq_sort($values));
$values = array(1, 1, 1, 1, 2, 3, 4);
print_r(uniq_sort($values));
$values = array(1, 1, 1, 1, 2, 3);
var_dump(uniq_sort($values));
Run Code Online (Sandbox Code Playgroud)
并输出:
Array
(
[0] => blue
[1] => purple
[2] => blue
[3] => yellow
[4] => blue
[5] => purple
[6] => blue
[7] => purple
[8] => red
[9] => yellow
[10] => green
)
Array
(
[0] => b
[1] => a
[2] => b
)
Array
(
[0] => 1
)
Array
(
[0] => 1
[1] => 3
[2] => 1
[3] => 4
[4] => 1
[5] => 2
[6] => 1
)
bool(false)
Run Code Online (Sandbox Code Playgroud)