= 10000) { // Adjust this number based on your available memory $this->sortAndWriteBuffer($buffer, $fileOutput); $buffer = []; } } // Sort and write any remaining rows $this->sortAndWriteBuffer($buffer, $fileOutput); fclose($fileInput); fclose($fileOutput); } protected function sortAndWriteBuffer(array $buffer, $fileOutput): void { usort($buffer, static function ($a, $b) { if ($a['country_code'] === $b['country_code']) { return (int) $a['state_id'] - (int) $b['state_id']; } return strcmp($a['country_code'], $b['country_code']); }); foreach ($buffer as $row) { fputcsv($fileOutput, $row); } } }