PHP Arrays - Separate Identical Values -


is there or standard way of doing this?

take following example:

$values = array(     'blue'     , 'blue'         , 'blue'     , 'blue'     , 'green'     , 'red'     , 'yellow'     , 'yellow'      , 'purple'     , 'purple'     , 'purple' ); 

i need separated no 2 identical values touching (unless there no possible solution -- in case either generating error, returning false or else acceptable).

here's above array (done hand) how trying change it:

$values = array(     'blue'     , 'purple'     , 'green'     , 'purple'     , 'blue'     , 'red'     , 'blue'     , 'yellow'     , 'blue'     , 'yellow'     , 'purple' ) 

the values won't in order in beginning -- simplicities sake.

any ideas? code me started in right direction?

this function should trick:

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; } 

example usage:

$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)); 

and output:

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] =>     [2] => b ) array (     [0] => 1 ) array (     [0] => 1     [1] => 3     [2] => 1     [3] => 4     [4] => 1     [5] => 2     [6] => 1 ) bool(false) 

Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -