3v4l.org

run code in 300+ PHP versions simultaneously
<?php $items = [ ['type' => 1, 'text' => 'A'], ['type' => 2, 'text' => 'B'], ['type' => 2, 'text' => 'C'], ['type' => 3, 'text' => 'D'], ['type' => 2, 'text' => 'E'], ['type' => 1, 'text' => 'F'], ['type' => 4, 'text' => 'G'], ['type' => 2, 'text' => 'H'], ['type' => 1, 'text' => 'I'], ['type' => 4, 'text' => 'J'], ['type' => 2, 'text' => 'K'], ['type' => 4, 'text' => 'L'], ['type' => 2, 'text' => 'M'], ['type' => 3, 'text' => 'N'], ['type' => 3, 'text' => 'O'], ['type' => 1, 'text' => 'P'], ['type' => 1, 'text' => 'Q'], ['type' => 2, 'text' => 'R'], ['type' => 3, 'text' => 'S'], ['type' => 2, 'text' => 'T'], ['type' => 3, 'text' => 'U'], ['type' => 2, 'text' => 'V'], ['type' => 3, 'text' => 'W'], ['type' => 2, 'text' => 'X'], ['type' => 4, 'text' => 'Y'], ['type' => 2, 'text' => 'Z'], ]; $maxConsecutive = 3; $grouped = []; foreach ($items as $row) { $grouped[$row['type']][] = $row; } ksort($grouped); $result = []; foreach ($grouped as &$group) { array_push($result, ...array_splice($group, 0, count($grouped) === 1 ? null : $maxConsecutive)); if ($group) { $grouped[] = $group; } } var_export($result);

preferences:
26.49 ms | 407 KiB | 5 Q