Sort files from a directory with PHP

Asked

Viewed 322 times

1

I have a directory where the files are stored as follows:

atos-oficiais-11-11-2019.pdf
atos-oficiais-14-10-2019.pdf
atos-oficiais-15-12-2019.pdf
....

We have developed a system so that these files are registered in the database from January/2020, but to not do this already in the 600 existing files in the directory, we create the following code:

$pasta = 'atos-oficiais/';
if(is_dir($pasta))
{
    $diretorio = dir($pasta);
    while(($arquivo = $diretorio->read()) !== false)
    {
         $quebrar = explode('atos-oficiais-',$arquivo);
         $extensao = explode('.',$quebrar[1]);
         list($dia,$mes,$ano) = explode('-',$extensao[0]);
         $data = $ano.'-'.$mes.'-'.$dia;
         if($data != '--')
         {
            $diasemana = array('Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado');
            $dataSemana = $data;
            $diasemana_numero = date('w', strtotime($dataSemana));
            mysqli_query($conexao,"INSERT INTO atos_oficiais VALUES(null,
                                    0,
                                    '".$data."',
                                    '".$diasemana[$diasemana_numero]."',
                                    '".$arquivo."')");
            $id = mysqli_insert_id($conexao);
            $cod = md5(strrev($id));
            mysqli_query($conexao,"UPDATE atos_oficiais SET IdCodAtosOficiais = '".$cod."' WHERE IdAtosOficiais = '".$id."';");                        
         }
    }
    $diretorio->close();
}
 else
{
    echo 'A pasta não existe.';
}

It is working perfectly, but we realize that the files are being registered randomly and we need to sort the files by date in an increasing way, that is, from the oldest to the most recent files. I’ve tried sorting directly by the file manager (I’m using Linux), but it didn’t help. How can I order them before I include them in the comic?

2 answers

0

You could do a method or function to read the directory and return the already sorted files, and then call the function or method to include passing the array with a list of already sorted documents. Something like that

while(($arquivo = $diretorio->read()) !== false) {
   $arquivos[] = $arquivo
}

arsort($arquivos);

Then call a function to insert passing the $files array as parameter

0

One way to do this would be to use the "scandir" function, it already returns the name of the files in alphabetical order. Here is an example

<?php
$caminho = "nome_da_pasta";
// Selecionar tudo exceto arquivos ocultos
$arquivos = preg_grep('/^([^.])/', scandir($caminho)); 

foreach ($arquivos as $arquivo) {
    print_r($arquivo . "<br>");
}
?>
  • Hello Bins. Actually it wouldn’t be alphabetical, since all files start with the letter "a".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.