I start with an array containing some 'ids' and some 'values'.
What I need is to organize the 'ids' in a new array to be, if possible, apart when the 'values' they are associated with are alike.
So I came up with a solution. If there is too much of a value type, the spreading is uneven. So if one of you has a different, better, solution, I'm all ears!
Here is what I came up with:
function discontinus_sort($to_sort, $order_by, $id){
while (count(array_count_values($to_sort)) >1) {
$order[] = [$id => key($to_sort) , $order_by => $to_sort[key($to_sort)]];
$holder = $to_sort[key($to_sort)];
unset($to_sort[key($to_sort)]);
reset($to_sort);
if (isset($to_sort[key($to_sort)])) {
while( $holder == $to_sort[key($to_sort)] ) {
next($to_sort);
}
}
}
while ($to_sort) {
$order[] = [$id => key($to_sort) , $order_by => $to_sort[key($to_sort)]];
unset($to_sort[key($to_sort)]);
}
return $order;
}
And for an example:
$test[0=>'red',1=>'red',2=>'red',3=>'crimson',4=>'aqua',5=>'chartreuse',6=>'green',7=>'chartreuse',8=>'red',9=>'crimson',10=>'crimson',11=>'aqua',12=>'aqua',13=>'green',14=>'crimson'];
$test_order = discontinus_sort($test, 'couleur', 'id');
foreach ($test_order as $key) {
echo '<div style="height: 100px; width: 100px; margin:5px; float: left; background-color:'.$key['couleur'].'; " ></div>';
}
If you change too many values, let's say by red, you'll end up with a big stack of red at the end.