Skip to content

Instantly share code, notes, and snippets.

@laurielylourenco
Last active March 28, 2024 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laurielylourenco/c37cc618fffc5e6caea1a8fd97d4b849 to your computer and use it in GitHub Desktop.
Save laurielylourenco/c37cc618fffc5e6caea1a8fd97d4b849 to your computer and use it in GitHub Desktop.
script-sorteio-csv
<?php
function sortearElemento(array $array)
{
$indiceSorteado = array_rand($array);
return $array[$indiceSorteado];
}
$call = function ($array) {
return str_getcsv($array, ";");
};
try {
// Nome do arquivo CSV e a coluna que será usada para o sorteio
$nomeArquivoCSV = 'sorteio.csv';
$colunaSorteio = 'descricao';
// Verifica se o arquivo existe
if (!file_exists($nomeArquivoCSV)) {
die("O arquivo CSV '{$nomeArquivoCSV}' não foi encontrado.");
}
// Lê o conteúdo do arquivo CSV
$linhas = file($nomeArquivoCSV, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Verifica se o arquivo está vazio
if (empty($linhas)) {
die("O arquivo CSV '{$nomeArquivoCSV}' está vazio ou mal formatado.");
}
$colunas = str_getcsv(array_shift($linhas), ";");
$colunaSorteioIndex = array_search($colunaSorteio, $colunas);
if ($colunaSorteioIndex === false) {
die("A coluna '{$colunaSorteio}' não foi encontrada no arquivo CSV.");
}
// Obtém os elementos da coluna de sorteio
$elementosSorteio = array_column(array_map($call, $linhas), $colunaSorteioIndex);
// Realiza o sorteio
$sorteado = sortearElemento($elementosSorteio);
// Exibe o resultado
echo "Sorte foi para : {$sorteado}";
} catch (\Throwable $th) {
echo "Erro: " . $th->getMessage();
}
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
nome;descricao
Caio;27346
Fagner;2345
Ana;0946
Juliana;4567
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment