[英]change colour if word selected array in php
我正在处理 php 代码,这很简单,我想为表中的每一行显示随机单词中的 1 个单词,并希望更改颜色。
<?php
$input = array(
'Hi',
'Welcome',
);
$rand_keys = array_rand($input, 2);
?>
<b style='color:green;'><?php echo $input[$rand_keys[0]];?> </b>
<b style='color:red;'><?php echo $input[$rand_keys[1]];?> </b>
我想做一件事:如果数组 word reslut = 嗨,如果欢迎以红色打印输出,那么这个词应该以绿色打印输出
请帮助我如何做到这一点>
二
这是你已经得到的结果:
<?php
$input = array(
'Hi',
'Welcome',
);
$rand_keys = array_rand($input, 2);
?>
本守则是正确的。
您可以使用速记if-else
并像这样回显 html 标签的样式:
<b style='color: <?= in_array('Hi', $input) ? 'green' : 'red' ?>'><?= $input[$rand_keys[0]];?> </b>
此语句的语法是:
condition ? true : false
我想你会发现数组 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>
您可以使用关联数组
<?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>";
}
因此,如果您真正需要的是与您正在构建的表格的每一行匹配颜色的随机问候语,那么您需要一个能够在您需要时随机选择一个的函数。 要获得随机条目,我们将使用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
的简写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.