简体   繁体   English

PHP从列表中随机选择

[英]PHP randomly select from a list

I am currently working with PHP code that random selects colors: 我目前正在使用随机选择颜色的PHP代码:

<div onclick="location.href='<?php the_permalink() ?>';" 
    style="cursor:pointer;background:#<?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?><?php 
        echo rand(0, 9); ?>;" 
    class="post bg thickbox" 
    id="thickbox post-<?php the_ID(); ?>">

What I would prefer to do is define a list of preferred colors in one PHP file, and then randomly sample an element from this list in the code above. 我更喜欢做的是在一个PHP文件中定义一个首选颜色列表,然后在上面的代码中从该列表中随机抽取一个元素。

What is the correct PHP code for randomly sampling such a list of colors? 用于随机抽样这样的颜色列表的正确PHP代码是什么? How would you define the list of colors? 你会如何定义颜色列表?

I would do like most have suggested, define your colors as an array in one php file: 我会像大多数人建议的那样,在一个php文件中将颜色定义为一个数组:

$colors = array("red", "blue", "#00ff00");

And then use array_rand to select one: 然后使用array_rand选择一个:

...background:<?= $colors[array_rand($colors, 1)] ?>;" class=...

只需创建一个颜色数组,然后使用rand(0,to)作为索引选择一个条目。

<?php

function getRandomColor(){
    $a = array('#ff5500', '#000066', '#555555');
    $indice = rand(0, count($a)-1);
    return $a[$indice];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM