我对这些问题的措辞很可怕,但我希望能够对我正在尝试做的事情有充分的了解。
我有7页和7张图片,图片全部是“waterfall_01.jpg”,“waterfall_02.jpg”等,最多7张。
到目前为止,我的代码很简单:
<?php
$cp = basename($_SERVER['PHP_SELF']);
$cf = dirname($_SERVER['PHP_SELF']);
?>
<img src="/img/waterfall_0<?php if ($cp == "about.php" || $cf == "/about"){ echo "1"; }?>.jpg" />
如何根据7个不同的页面更改此代码以回显介于1和7之间的不同数字(其中一些页面的文件夹下方有一些文件夹在下拉菜单中显示)。
从技术上讲,我可以写一个非常长的行:
<img src="/img/waterfall_0<?php
if ($cp == "home.php"){ echo "1"; }
if ($cp == "about.php" || $cf == "/about"){ echo "2"; }
if ($cp == "products.php" || $cf == "/products"){ echo "3"; }
if ($cp == "services.php" || $cf == "/services"){ echo "4"; }
if ($cp == "gallery.php" || $cf == "/gallery"){ echo "5"; }
if ($cp == "faq.php"){ echo "6"; }
if ($cp == "contact.php"){ echo "7"; }
?>.jpg" />
我对PHP不是那么好,我不确定上述是否是最佳或正确的方式,所以所有的帮助都表示赞赏!
测试服务器为http://www.mrobertsdesign.ca/home.php
提前致谢!
答案 0 :(得分:4)
<?php
$requestedURI = $_SERVER['REQUEST_URI'];
$images = array(
"/home" => "1",
"/about" => "2",
"/products" => "3",
"/services" => "4",
"/gallery" => "5",
"/faq" => "6",
"/contact" => "7",
);
?>
<img src="/img/waterfall_0<?= $images[$requestedURI]; ?>.jpg"/>
只需确保您的网址与数组密钥匹配。
答案 1 :(得分:4)
Justin Workman和Satish Sharma的两个答案都是可行的解决方案。但为什么不通过另一种选择。 切换语句。
$url = $_SERVER['REQUEST_URI'];
switch ($url) {
case '/about':
case '/about.php':
$img = 2;
break;
case '/contact':
case '/contact.php':
$img = 3;
break;
......
default:
$img = '1';
}
然后将变量输出到img标签中。
答案 2 :(得分:2)
你需要使用if else
<?php
$cp = basename($_SERVER['PHP_SELF']);
$cf = dirname($_SERVER['PHP_SELF']);
if($cp == "home.php")
{
$img_src = "1.jpg";
}
else if($cp == "about.php" || $cf == "/about"))
{
$img_src = "2.jpg";
}
else if($cp == "products.php" || $cf == "/products")
{
$img_src = "3.jpg";
}
else if($cp == "services.php" || $cf == "/services")
{
$img_src = "4.jpg";
}
else if($cp == "gallery.php" || $cf == "/gallery")
{
$img_src = "5.jpg";
}
else if($cp == "faq.php")
{
$img_src = "6.jpg";
}
else if($cp == "contact.php")
{
$img_src = "7.jpg";
}
?>
<img src="/img/waterfall_0<?php echo $img_src;?>" />