3 回答

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
我希望這就是你想要的
<?php
$rand = rand(1,10);
switch ($rand) {
case "1":
$profile_pic = "/defaults/profile_pic1.png";
echo "1";
break;
case "2":
$profile_pic = "/defaults/profile_pic2.png";
echo "2";
break;
case "3":
$profile_pic = "/defaults/profile_pic3.png";
echo "3";
break;
case "4":
$profile_pic = "/defaults/profile_pic4.png";
echo "4";
break;
case "5":
$profile_pic = "/defaults/profile_pic5.png";
echo "5";
break;
case "6":
$profile_pic = "/defaults/profile_pic6.png";
echo "6";
break;
case "7":
$profile_pic = "/defaults/profile_pic7.png";
echo "7";
break;
case "8":
$profile_pic = "/defaults/profile_pic8.png";
echo "8";
break;
case "9":
$profile_pic = "/defaults/profile_pic9.png";
echo "9";
break;
case "10":
$profile_pic = "/defaults/profile_pic10.png";
echo "10";
break;
default:
$profile_pic = "/defaults/profile_picDEFAULT.png";
echo "default PHOTO";
}
?>

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
我真的不明白你為什么要在switch這里使用聲明。在改進(jìn)代碼方面 - 您只能使用 2 行。隨著if和switch它的每個(gè)條件2-3行,它是最壞的編程習(xí)慣你可能會(huì)拿出。只要給我一個(gè)很好的理由,為什么。
如果您仔細(xì)閱讀 PHP 文檔,則可以使用字符串運(yùn)算符頁面,其中解釋了如何解決您的問題:
連接運(yùn)算符 ( .),它返回其左右參數(shù)的連接。
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
所以你可以簡(jiǎn)單地用
$rand = rand(1,10);
$profile_pic = "/defaults/profile_pic" . $rand . ".png";
或者你可能會(huì)偶然發(fā)現(xiàn)Variable parsing,它指出:
當(dāng)一個(gè)字符串用雙引號(hào)或 heredoc 指定時(shí),變量在其中解析。
$juice = "apple";
echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
所以你可以做的是:
$rand = rand(1,10);
$profile_pic = "/defaults/profile_pic${rand}.png";

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您在圖像路徑中使用相同的隨機(jī)數(shù),則不需要 if 或 switch 循環(huán)。您可以使用以下代碼。$rand = rand(1,10) ;
$profile_pic = "/defaults/profile_pic$rand.png"; 如果您有隨機(jī)數(shù)和圖像的映射,則將其存儲(chǔ)在數(shù)組中并訪問它。$rand_image = array(1=>"firstimg.png", 2=>"2.png") ;
$profile_pic = "/defaults/profile_pic".$rand_image[$rand];
- 3 回答
- 0 關(guān)注
- 322 瀏覽
添加回答
舉報(bào)