问题
I have this code which displays logos with a link to a video file. I frequently upload files and I want to keep thinks in order. At the moment it just attaches them in order of name. So for example if I upload a movie and haven't gotten around to uploading a photo with the exact same name then from that point on any photos will be displayed with mismatching links.
What I'd like to do is display a temporary photo if the name doesn't match.
I know you can do something like if(array[1] === array2[1]) but the file extensions would be different so that would return false every time.
Code:
<?php
$images = glob('./*.{jpeg,jpg,png}', GLOB_BRACE);
$movies = glob('./*.{mp4,m4v}', GLOB_BRACE);
$movieLink = 0;
foreach($images as $image) {
echo '<a href="' .$movies[$movieLink].'">
<img src="'.$image.'" style="width:300px;height:350px;border:0;">
</a>';
$movieLink++;
}
?>
Example of server directory (400+ movies and >30 photos):
Dir1
- Movie1.mp4 ↰__ correct pair
- Movie1.png ↲
- Movie2.m4v ↰__ correct pair
- Movie2.png ↲
- Movie3.mp4 ↰__ incorrect pair
- Movie4.mp4 ↲
- Movie4.png ←-- no image to pair with
When this runs it displays 3 photos side by side which when clicked the first 2 (Movie1.png && Movie2.png) you are taken to the correct movies for each. However, when you click "Movie 4.png" you are taken to "Movie3.mp4".
回答1:
Use pathinfo($filename, PATHINFO_FILENAME)
to construct a lookup array for easy verification. The lookup array uses "extensionless" movie filenames as keys which are paired with the image filename (with its extension).
You should be looping the $movies
array, if your project logic states that there will always be more movies than images.
$movies = glob('./*.{mp4,m4v}', GLOB_BRACE);
$images = glob('./*.{jpeg,jpg,png}', GLOB_BRACE);
foreach ($images as $image) {
$lookup[pathinfo($image, PATHINFO_FILENAME)] = $image;
}
foreach ($movies as $movie) {
$image = $lookup[pathinfo($movie, PATHINFO_FILENAME)] ?? 'default.jpg';
echo '<a href="' . $movie . '">
<img src="' . $image . '" style="width:300px;height:350px;border:0;">
</a>';
}
The above snippet is not tested, but it should be pretty close. In case you are unfamiliar, the ??
is the null coalescing operator. It basically says assign the lookup value unless it is missing, in which case use the default value.
Here's a demo of the lookup array construction: https://3v4l.org/HJhVR
来源:https://stackoverflow.com/questions/55783664/check-for-similar-text-in-arrays-php