早上好,我有一个数组,可以包含4到4000个条目,我必须在4个人之间平均分配数量。我正在努力使我的代码按需执行,
您可以看到我对数组的分配不是所期望的。
Array([0] => Array([0] => 80 [7] => 40 [8] => 50)[1] => Array([1] => 80)[2] =>数组([2] => 70 [6] => 30)[3] =>数组([3] =>60 [5] => 40))
数组0共有150数组1共有80个数组2共有100数组3的总数为100
<?php
arrayBuilder();
function arrayBuilder()
{
$list_of_items = [80, 20, 30, 40, 50, 60, 70, 80];
rsort($list_of_items);
$number_of_cont = 4;
$weight_of_items = array_sum($list_of_items);
$weight_per_cont = ($weight_of_items/$number_of_cont);
$containers = [];
$sumArray = $newArray = [];
$containersSorted = buildArray($list_of_items,$number_of_cont,$containers,$weight_per_cont);
$itemsNotAdded = itemsNotINArray($list_of_items, $containersSorted);
foreach ($containersSorted as $k => $subArray) {
foreach ($subArray as $id => $value) {
if(isset($sumArray[$k])) {
$sumArray[$k] += $value;
}else{
$sumArray[$k] = $value;
}
}
}
sort($sumArray);
$itemsNotAdded = array_values($itemsNotAdded);
foreach($itemsNotAdded as $key => $value){
foreach($sumArray as $minkey => $minval){
if($minkey == $key) {
$containersSorted[$key][] = $value;
unset($itemsNotAdded[$key]);
}
}
}
print_r($containersSorted);
};
function itemsNotINArray($list_of_items, $containersSorted){
foreach($containersSorted as $conid => $conval){
foreach($list_of_items as $key => $value){
if(key_exists($key,$conval)){
unset($list_of_items[$key]);
continue;
}
}
}
return $list_of_items;
};
function getMisMatchKey($itemsNotAdded, $containersSorted){
}
function buildArray($list_of_items,$number_of_cont,$containers,
$weight_per_cont){
foreach($list_of_items as $key => $item) {
for ($i = 0; $i < $number_of_cont; $i++) {
$total = (isset($containers[$i])) ? array_sum($containers[$i]) : 0;
if (($total + $item) < $weight_per_cont) {
$containers[$i][$key] = $item;
break;
}
}
}
return $containers;
};
?>
应该均匀地解决
数组([0] =>数组([0] => 80 [7] => 20)[1] =>数组([1] =>80 [6] => 30)[2] =>数组([2] => 70 [8] => 40)[3] =>数组([3] => 60 [5] => 50]
您可以使用array_chunk
将一个数组的数据平均分布到许多其他数组+最后一个数组,而该数组可能少于其他数组。
请参见手册:array_chunk