如果单词在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>

我想做一件事:如果数组单词 reslut = Hi 如果欢迎打印为红色,则该单词应打印为绿色


请帮我怎么做>



红颜莎娜
浏览 99回答 4
4回答

繁花不似锦

我想你会发现你的数组 array_rand 中只有两个元素不会很有用。尝试改用 rand() 并结合 if 语句。您可以在 php 沙盒中尝试一下:<?php&nbsp; $input = array('Hi','Welcome');&nbsp; $index = rand(0,1);&nbsp; if($input[$index] == "Hi"){ ?>&nbsp;&nbsp; &nbsp; &nbsp;<div style='color:green;'><?php echo $input[0]; ?> </div>&nbsp; &nbsp; &nbsp;<div style='color:red;'&nbsp; ><?php echo $input[1]; ?> </div><?php }else if(1==1){?>&nbsp; &nbsp; &nbsp;<div style='color:blue;'><?php echo $input[0];&nbsp; &nbsp;?> </div>&nbsp; &nbsp; &nbsp;<div style='color:blue;'><?php echo $input[1]; } ?> </div>

翻翻过去那场雪

这是您已经得到的结果:<?php&nbsp; $input = array(&nbsp; &nbsp; 'Hi',&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; 'Welcome',&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; );&nbsp; $rand_keys = array_rand($input, 2);?>这个代码是正确的。

江户川乱折腾

你可以使用关联数组<?php&nbsp; &nbsp; $input = array(&nbsp; &nbsp; &nbsp; &nbsp; 'green' => 'Hi',&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'red' => 'Welcome',&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; );&nbsp; &nbsp; $keys = array_keys($input); // Makes colors array: green and red&nbsp; &nbsp; shuffle($keys);// randomizes colors order&nbsp; &nbsp; foreach($keys as $color) {&nbsp; &nbsp; &nbsp; &nbsp; echo "<b style='color: $color;'>$input[$color]</b>";&nbsp;&nbsp; &nbsp; }

米琪卡哇伊

因此,如果您真正需要的是为您正在构建的表格的每一行提供匹配颜色的随机问候语,那么您需要一个能够在您需要时随时选择随机问候语的函数。要获得随机条目,我们将使用rand:function getRandomGreeting(): string{&nbsp; &nbsp; // we immediately define a color for each greeting&nbsp; &nbsp; // that way we don't need an if condition later comparing the result we got&nbsp; &nbsp; $greetings = [&nbsp; &nbsp; &nbsp; &nbsp; ['greeting' => 'Hi', 'color' => 'green'],&nbsp; &nbsp; &nbsp; &nbsp; ['greeting' => 'Welcome', 'color' => 'red'],&nbsp; &nbsp; ];&nbsp; &nbsp; /*&nbsp; &nbsp; Here we choose a random number between 0 (because arrays are zero-indexed)&nbsp; &nbsp; and length - 1 (for the same reason). That will give us a random index&nbsp; &nbsp; which we use to pick a random element of the array.&nbsp; &nbsp; Why did I make this dynamic?&nbsp; &nbsp; Why not just put 1 if I know indices go from 0 to 1?&nbsp; &nbsp; This way, if you ever need to add another greeting, you don't need&nbsp; &nbsp; to change anything in the logic of the function. Simply add a greeting&nbsp; &nbsp; to the array and it works!&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; $chosenGreeting = $greetings[rand(0, count($greetings) - 1)];&nbsp; &nbsp; return '<b style="color:'.$chosenGreeting['color'].';">'.$chosenGreeting['greeting'].'</b>';}然后在您的表格中,您只需要调用该函数:<td><?= getRandomGreeting() ?> [...other content of cell...]</td>请注意,这<?=是<?php echo.
打开App,查看更多内容
随时随地看视频慕课网APP