拆分数组,但每个数组的总和不超过最大值,否则推送到下一个数组索引 [英] Split array but sum of each array not to exceed a max value else push to next array index
问题描述
我有两个数组,数组1是施主数组,它具有一系列值(在我的示例中不一定是相等的值)。数组2是理想的结果,它将存储一系列子数组,这些子数组的值来自数组1,其中每个子数组的总和不超过25。如果超过,超出的部分将被推送到数组2中的下一个索引,其中规则将
I have two arrays, Array 1 being a donor array which has a series of values (not necessarily equal values as in my example). Array 2 is the desired result and would store a series of sub arrays with values from Array 1 where each sub array's total sum would not exceed 25. If it does, the excess would get pushed to the next index in Array 2 where the rules would also apply.
捐赠者数组(数组1):
$a1=array(10,10,10,10,10,10,10,10,10,10);
所需的输出(数组2):
Array
(
[0] => 10,10,5
[1] => 5,10,10
[2] => 10,10,5
[3] => 5,10,10
)
这是我尝试的代码,但收到错误:
Here the code I tried but it gets an error:
通知:未定义的偏移量: 10 ...等。
$a1=array(10,10,10,10,10,10,10,10,10,10);
$a2=array();
$count=count($a1);
for($i=0;$i<$count;$i++){
$a2count=array_sum($a2);
if($a2count>25){
$i=$i+1;
$a2[$i]=$a1[$i];
}
else{
$a2[$i]=$a1[$i];
}
}
print_r($a2);
我不知道要实现什么逻辑并获得想要的结果。
I don't know what logic to implement and get result I'm looking for.
推荐答案
在这里,您可以:逻辑并不难。希望对您有所帮助。
Here you go: The logic is not so hard. Hope it helps.
<?php
$a1=array(10,10,10,10,10,10,10,10,10,10);
$a2 = [];
$a3 = [];
$m = 0;
for($i = 0; $i < count($a1); ++$i){
$m += $a1[$i];
if($m > 25){
$n = $m % 25;
if(array_sum($a2) != 25){
$a2[] = $n;
}
$a3[] = implode(',', $a2);
$a2 = [];
$m = $n;
$a2[] = $n;
} else{
$a2[] = $a1[$i];
}
}
$a3[] = implode(',', $a2);
print_r($a3);
?>
这篇关于拆分数组,但每个数组的总和不超过最大值,否则推送到下一个数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!