[英]Check if filename from directory exists as a value in database
我在一個目錄中有一堆 .png 文件,它們的名稱與數據庫中的值相同。 我想檢查數據庫中是否存在文件名(不帶“.png”)。
目前我正在使用此代碼來顯示數據庫中的標志
<?php
$result = mysql_query("SELECT `country` FROM `countries`");
while($row = mysql_fetch_array($result)) {;
?>
<img src="images/countries/<?php echo $row['country']?>.png" />
<?php }; ?>
我也想顯示不在數據庫中的標志,但隨后以灰度顯示。
我想出了這個代碼來從目錄中獲取所有標志
<?php
$directory = "images/countries/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
echo '<image src="'.$image.'" class="flaginactive"/>'; //show all flags as inactive
echo basename($image, '.png'); //get file name with .png
}
?>
但不知何故,我被困住了,並且一無所知,我如何才能在 if 語句中同時獲得它們。
有人可以告訴我如何以最好的方式解決這個問題。 我知道我正在使用舊的 mySQL 函數。
有很多方法可以實現這一目標。 我將介紹一個。
首先將數據庫中的名稱加載到數組中。 然后檢查數組中目錄的枚舉文件名是否存在,以確定元素的類。
如果在數據庫中找不到目錄中的文件,則元素顯示為不活動。
<?php
$directory = "images/countries/";
//Lets save all the file names in the database to an array
$dbImages = array();
$result = mysql_query("SELECT `country` FROM `countries`");
while($row = mysql_fetch_array($result)) {
array_push($dbImages, $directory . $row['country'] . '.png');
}
//Lets go through all the files in the directory and see if they are in the $dbImages array
$images = glob($directory . "*.png");
foreach($images as $image)
{
//Decide the class attribute based on the existence of the file name in $dbImages array
if (in_array($image, $dbImages))
$classAttribute = '';
else
$classAttribute = 'class="flaginactive"'
echo '<image src="'.$image.'" ' . $classAttribute . ' />';
}
?>
您可以像這樣file_exists()函數
<?php
$directory = "images/countries/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $directory . $image . '.png')) //Files exists goes here
{
echo '<image src="'.$image.'" class="flaginactive"/>'; //show all flags as inactive
echo basename($image, '.png'); //get file name with .png
}
}
?>
遍歷數據庫中的標志並將它們存儲在數組中。 然后在遍歷目錄中的標志時,檢查文件是否在數組中。 (假設目錄中的文件在數據庫中具有相同的名稱,這似乎不適用於您的情況。我的答案將需要進行一些調整。)
<?php
$result = mysql_query("SELECT `country` FROM `countries`");
$selectedFlags = array();
while($row = mysql_fetch_array($result)) {
$selectedFlags[] = $row['country'];
}
$directory = "images/countries/";
$images = glob($directory . "*.png");
foreach($images as $image) {
echo '<image src="'.$image . '"';
if (!in_array($image, $selectedFlags))
echo ' class="flaginactive"';
echo ' />';
// not sure why the next line is here since your sample image didn't have it but I'll leave it in
echo basename($image, '.png'); //get file name with .png
}
?>
PS,花括號( {
)后不需要分號( ;
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.