suppose i have:
$val = [1, 2, 3, 4, 5, 6, 7, 8];
$s = 3;
step 1: foreach $val
find how many times $s
is found in it. This is simple enough
foreach($val as $c){
if($c > $s) {
$total = floor($c / $s);
$remainder = $c % $s;
} else {
$total = floor($s / $c);
$remainder = $s % $c;
}
}
step 2: build an array that will show just that. For example:
// 3 doesn't go in 1
['segment' => 1]
// 3 doesn't go in 2
['segment' => 2]
// 3 goes once in 3
['segment' => 3]
// 3 goes once in 4 and reminder is 1
['segment' => 3]
['segment' => 1]
// 3 goes once in 5 and reminder is 2
['segment' => 3]
['segment' => 2]
// 3 goes twice in 6 and reminder is 0
['segment' => 3]
['segment' => 3]
// 3 goes twice in 7 and reminder is 1
['segment' => 3]
['segment' => 3]
['segment' => 1]
// 3 goes twice in 8 and reminder is 2
['segment' => 3]
['segment' => 3]
['segment' => 2]
and so on
i was trying something like the code below, but cant get it to work:
foreach($val as $c){
if($c > $s) {
$total = floor($c / $s);
$remainder = $c % $s;
$segment = $s;
} else {
$total = floor($s / $c);
$remainder = $s % $c;
$segment = $c;
}
$totalLoop = $c > $s ? $total + $remainder : 1;
var_dump('total: ' . $total . ', reminder: ' . $remainder . ', segment : ' . $segment);
for($i = 1; $i <= $totalLoop; $i++) {
$segment= $c > $s && $totalLoop == $i ? $remainder : $segment;
var_dump('segment: ' . $segment);
}
}
any ideas?
Using the modulus operator (which determines the remainder of the division) and then calculating how many times $s fits in your $c is the quickest approach I could muster. Should look something like this:
$times should be your result. You should then be able to build the array you're looking for with $times and $mod:
Looking at your second loop, it seems to that you are currently always only getting exactly one segment, as you seem to be overwritin the variable every time the loop runs. Is that correct?
UPDATE:
So here's what works for me (given my understanding of what you want to achieve):
The
prettyPrint
function is borrowed from here.