4 回答

TA貢獻1851條經(jīng)驗 獲得超4個贊
我想你會發(fā)現(xiàn)你的數(shù)組 array_rand 中只有兩個元素不會很有用。嘗試改用 rand() 并結(jié)合 if 語句。
您可以在 php 沙盒中嘗試一下:
<?php
$input = array('Hi','Welcome');
$index = rand(0,1);
if($input[$index] == "Hi"){ ?>
<div style='color:green;'><?php echo $input[0]; ?> </div>
<div style='color:red;' ><?php echo $input[1]; ?> </div>
<?php }else if(1==1){?>
<div style='color:blue;'><?php echo $input[0]; ?> </div>
<div style='color:blue;'><?php echo $input[1]; } ?> </div>

TA貢獻2065條經(jīng)驗 獲得超14個贊
這是您已經(jīng)得到的結(jié)果:
<?php
$input = array(
'Hi',
'Welcome',
);
$rand_keys = array_rand($input, 2);
?>
這個代碼是正確的。

TA貢獻1851條經(jīng)驗 獲得超5個贊
你可以使用關聯(lián)數(shù)組
<?php
$input = array(
'green' => 'Hi',
'red' => 'Welcome',
);
$keys = array_keys($input); // Makes colors array: green and red
shuffle($keys);// randomizes colors order
foreach($keys as $color) {
echo "<b style='color: $color;'>$input[$color]</b>";
}

TA貢獻1998條經(jīng)驗 獲得超6個贊
因此,如果您真正需要的是為您正在構(gòu)建的表格的每一行提供匹配顏色的隨機問候語,那么您需要一個能夠在您需要時隨時選擇隨機問候語的函數(shù)。要獲得隨機條目,我們將使用rand:
function getRandomGreeting(): string
{
// we immediately define a color for each greeting
// that way we don't need an if condition later comparing the result we got
$greetings = [
['greeting' => 'Hi', 'color' => 'green'],
['greeting' => 'Welcome', 'color' => 'red'],
];
/*
Here we choose a random number between 0 (because arrays are zero-indexed)
and length - 1 (for the same reason). That will give us a random index
which we use to pick a random element of the array.
Why did I make this dynamic?
Why not just put 1 if I know indices go from 0 to 1?
This way, if you ever need to add another greeting, you don't need
to change anything in the logic of the function. Simply add a greeting
to the array and it works!
*/
$chosenGreeting = $greetings[rand(0, count($greetings) - 1)];
return '<b style="color:'.$chosenGreeting['color'].';">'.$chosenGreeting['greeting'].'</b>';
}
然后在您的表格中,您只需要調(diào)用該函數(shù):
<td><?= getRandomGreeting() ?> [...other content of cell...]</td>
請注意,這<?=是<?php echo.
- 4 回答
- 0 關注
- 131 瀏覽
添加回答
舉報