4 回答
TA贡献1851条经验 获得超4个赞
我想你会发现你的数组 array_rand 中只有两个元素不会很有用。尝试改用 rand() 并结合 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条经验 获得超13个赞
这是您已经得到的结果:
<?php
$input = array(
'Hi',
'Welcome',
);
$rand_keys = array_rand($input, 2);
?>
这个代码是正确的。
TA贡献1851条经验 获得超5个赞
你可以使用关联数组
<?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条经验 获得超6个赞
因此,如果您真正需要的是为您正在构建的表格的每一行提供匹配颜色的随机问候语,那么您需要一个能够在您需要时随时选择随机问候语的函数。要获得随机条目,我们将使用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>';
}
然后在您的表格中,您只需要调用该函数:
<td><?= getRandomGreeting() ?> [...other content of cell...]</td>
请注意,这<?=是<?php echo.
- 4 回答
- 0 关注
- 98 浏览
添加回答
举报