Vivil - 1 year ago 70
PHP Question

# Split array but sum of each array not to exceed a max value else push to next array index

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.

Donor array (Array 1):

``````\$a1=array(10,10,10,10,10,10,10,10,10,10);
``````

Desired output (Array 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:

Notice: Undefined offset: 10...etc.

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

?>
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download