尽可能将多个数组的元素均匀分布

2021-11-19 09:14:18   工作备份

 

  1. $array = array_values($array);//二维数组,其中的元素就是需要均匀分布的数组
  2. $temp_array = [];
  3. foreach ($array as $item){
  4. $temp_array[count($item)][] = $item;
  5. }
  6. ksort($temp_array);
  7. $array = [];
  8. //按照子元素的数组长度,从小到大重新排序,重组数组
  9. foreach ($temp_array as $item){
  10. foreach ($item as $value){
  11. $array[] = $value;
  12. }
  13. }
  14. $order = [];
  15. while ($enterprises_staffs = array_shift($array)) {
  16. $temp = array_column($enterprises_staffs, 'id');
  17. if (empty($order)) {
  18. $order = $temp;
  19. } else {
  20. $score = round(count($order) / count($temp), 2);
  21. $index = count($order) / 2;
  22. $left = ceil(count($temp) / 2);
  23. $right = count($temp) - $left;
  24. $left_nums = $right_nums = 0;
  25. $key = 1;
  26. foreach ($temp as $id) {
  27. if ($left_nums < $left) {
  28. $l_index = $index - $key * $score;
  29. while (isset($order["{$l_index}"])) {
  30. $l_index -= 0.1;
  31. }
  32. $order["{$l_index}"] = $id;
  33. ++$left_nums;
  34. ++$key;
  35. if ($left_nums == $left) {
  36. $key = 0;
  37. }
  38. } elseif ($right_nums < $right) {
  39. $r_index = $index + $key * $score;
  40. while (isset($order["{$r_index}"])) {
  41. $r_index += 0.1;
  42. }
  43. $order["{$r_index}"] = $id;
  44. ++$right_nums;
  45. ++$key;
  46. if ($right_nums == $right) {
  47. $key = 0;
  48. }
  49. }
  50. }
  51. ksort($order);
  52. $order = array_values($order);
  53. }
  54. }
  55. var_dump($order);