Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

SortCsv.php 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. class SortCsv extends Command
  5. {
  6. /**
  7. * The name and signature of the console command.
  8. *
  9. * @var string
  10. */
  11. protected $signature = 'sort:csv';
  12. /**
  13. * The console command description.
  14. *
  15. * @var string
  16. */
  17. protected $description = 'Sort the cities CSV file by country code and state code';
  18. /**
  19. * Execute the console command.
  20. */
  21. public function handle(): void
  22. {
  23. $inputPath = resource_path('data/cities.csv');
  24. $outputPath = resource_path('data/cities-sorted.csv');
  25. $fileInput = fopen($inputPath, 'rb');
  26. $fileOutput = fopen($outputPath, 'wb');
  27. // Write header to output file
  28. if (($header = fgetcsv($fileInput, 1000, ',')) !== false) {
  29. fputcsv($fileOutput, $header);
  30. }
  31. $buffer = [];
  32. while (($row = fgetcsv($fileInput, 1000, ',')) !== false) {
  33. $buffer[] = array_combine($header, $row);
  34. // When buffer reaches some size, sort and write to file
  35. if (count($buffer) >= 10000) { // Adjust this number based on your available memory
  36. $this->sortAndWriteBuffer($buffer, $fileOutput);
  37. $buffer = [];
  38. }
  39. }
  40. // Sort and write any remaining rows
  41. $this->sortAndWriteBuffer($buffer, $fileOutput);
  42. fclose($fileInput);
  43. fclose($fileOutput);
  44. }
  45. protected function sortAndWriteBuffer(array $buffer, $fileOutput): void
  46. {
  47. usort($buffer, static function ($a, $b) {
  48. if ($a['country_code'] === $b['country_code']) {
  49. return (int) $a['state_id'] - (int) $b['state_id'];
  50. }
  51. return strcmp($a['country_code'], $b['country_code']);
  52. });
  53. foreach ($buffer as $row) {
  54. fputcsv($fileOutput, $row);
  55. }
  56. }
  57. }