user4381753
user4381753

Reputation: 71

Remove n items after every n items from an array

I have an array of numbers 10, 20, 50, 40, 30, 80, 90, 100, 80

There could be as many numbers as possible. I want to first sort them in descending order and then want to remove n number of items after every n numbers of items and then get the total. So for eg. if i want to remove 2 items after every 3 items from the above array then the result should be

100, 90, 80, 40, 30, 20 = 360

I wrote some code but its not working correctly.

    <?php
function offer($items, $buyItems, $get) {
$offerType = $buyItems+1;
$x = $items;
rsort($x);
$y = count($x);

for($i=$y; $i> 0; $i -= $offerType ) {
        $index = $i-1;


        array_splice($x, $index, 1);
    }


$arrlength = count($x);

for($z = 0; $z < $arrlength; $z++) 
{
    echo $x[$z];
    echo "\n";

}
echo "Total = " . array_sum($x) . "\n";
}
offer(array(2, 5, 7,16, 6, 8, 40, 90), 2, 1);
?>

Upvotes: 1

Views: 65

Answers (1)

shudder
shudder

Reputation: 2101

I would cut sorted array into chunks (lenght = good+remove) and then deal with each of them (cut off and store/display).

function offer($items, $buyItems, $get) {

    rsort($items);
    $sum = 0;

    foreach (array_chunk($items, $buyItems + $get) as $group) {
        foreach (array_slice($group, 0, $buyItems) as $item) {
            echo $item . "\n";
            $sum += $item;
        }
    }

    echo "Total = " . $sum . "\n";
}

Btw. New line "\n" won't work in browser view (source only) - you need html <br> for line breaks.

Upvotes: 1

Related Questions