In this question PHP file listing multiple file extensions, the answer is given for a glob directory, does anyone have a succinct solution similar to the one given but where the files are contained in an array? For example,
$fileType1_ext = array("jpg", "png","bmp", "etc");
$fileType2_ext = array("avi", "mov", "mp4", "etc");
$files = array("filename1.jpg", "filename2.png", "filename3.bmp", "filename1.avi", "filename2.mov", "filename3.mp4","filename2.axy");
What I would like to see is all the files that have the same name irrespective of the extension:
`$pairedFiles[0] = array("filename1.jpg", "filename1.avi");`
`$pairedFiles[1] = array("filename2.png", "filename2.avi","filename2.axy");
etc..`
What I am currently doing, and it's messy, and it is pointless listing the code, as it is not the way I would prefer to do it but is based on getting extension of the set $files
into $fileExt
array and then using
$typeIndex = array_search($filesExt, $fileType1_ext);
which requires multiple loops, stripping file names etc.
CodePudding user response:
I would use a foreach
to loop over the array to build a multidimensional array using the basename as the index. From there you can filter out arrays with less than 2 items.
$fileType1_ext = array("jpg", "png","bmp", "etc");
$fileType2_ext = array("avi", "mov", "mp4", "etc");
$files = array("filename1.jpg", "filename2.png", "filename3.bmp", "filename1.avi", "filename2.mov", "filename3.mp4","filename2.axy","filename4.mp4");
$matches = [];
foreach( $files as $filename ) {
$base_name = substr($filename, 0, strrpos($filename, '.'));
$matches[$base_name][] = $filename;
}
// Filter out arrays with less than 2 matches
$filtered_matches = array_filter($matches, function($array) {
return count($array) >= 2;
});
CodePudding user response:
A possible solution would be to inspect your $files
array and generate a list of filenames without the extensions. Then use a pattern matching function to perform a lookup of the $files
array and perform a search.
Perhaps something like the following:
$files = array(
"filename1.jpg",
"filename2.png",
"filename3.bmp",
"filename1.avi",
"filename2.mov",
"filename3.mp4",
"filename2.axy"
);
$filenames = array_unique(
array_map(function ($value) {
return explode('.', $value)[0];
}, $files)
);
foreach ($filenames as $filename) {
$result[] = preg_grep("/$filename/", $files);
}