Question:
I have an array with the following filenames:
$lista_archivos[0] = '2019.pdf';
$lista_archivos[1] = '2019.zip';
$lista_archivos[2] = '2018.pdf';
$lista_archivos[3] = '2018.xls';
$lista_archivos[4] = '2019.xls';
$lista_archivos[5] = '2019.xlsx';
What I want to do is group all the elements that are called the same in an array index, in order to obtain a result like this:
$archivos_juntos[0] = '2019.pdf-2019.zip-2019.xls-2019.xlsx';
$archivos_juntos[1] = '2018.pdf-2018.xls';
The problem I have is that I can't come up with a function that allows me to do what I say. Try something separating the names of the formats, like this:
foreach($lista_archivos as $archivo) {
$archivo = explode('.', $archivo);
$nombre = $archivo[0]; //Usando echo imprime, por ejemplo: 2019
$extension = $archivo[1]; //Usando echo imprime, por ejemlo: pdf
}
But I only get to this point, I don't know how I should compare so that it finds the other names the same but with a different format, and that it does not leave them repeated.
I hope someone can help me with this problem, thanks.
Answer:
You can solve it by splitting the string with functions like strstr()
to get the extensions, substr()
and strrpos()
to get the names, and checking the indices with isset()
as follows:
foreach($lista_archivos as $archivo) {
$ext = strstr($archivo, '.');
$nom = substr($archivo,0,strrpos($archivo, '.'));
isset($archivos_juntos[$nom]) ?
$archivos_juntos[$nom].= '-'.$archivo
: $archivos_juntos[$nom]=$archivo;
}
You can see the code working in the following link:
I hope it is what you are looking for, greetings.