array_rand()数组到字符串?

Wor*_*sor 1 php arrays random implode

我有一个数组,如:

$hex = array("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
Run Code Online (Sandbox Code Playgroud)

我想将6个随机元素作为字符串返回(例如1a3564):

$random_color = array_rand($hex,6);
Run Code Online (Sandbox Code Playgroud)

我认为爆发$ random_color可以解决问题:

echo implode($random_color);
Run Code Online (Sandbox Code Playgroud)

但是array_rand()存储了父数组中元素的位置,而不是这个数组元素,所以我得到类似的东西:

259111213而不是259bcd.

我知道这正是我想要的:

echo $hex[$random_color[0]];
echo $hex[$random_color[1]];
echo $hex[$random_color[2]];
echo $hex[$random_color[3]];
echo $hex[$random_color[4]];
echo $hex[$random_color[5]];
Run Code Online (Sandbox Code Playgroud)

但:

  • 有没有办法在array_rand()中存储数组元素?为什么它首先存储元素的位置而不是元素?

  • 做我想做的最好的方法是什么?

  • 为什么array_rand()绝不选择一个字母作为第一个元素,几乎从不作为第二个/第三个(99%的生成颜色看起来像11111a 12345c 123456)?

out*_*tis 5

由于项目都不同,您可以将它们转换为键而不是值,然后array_rand在结果上使用:

implode('', array_rand(array_flip($hex), 6));
Run Code Online (Sandbox Code Playgroud)

但是,可能有更好的方法来实现您的总体目标.例如,如果总体目标允许重复数字,只需生成从0到0xFFFFFF的随机数并转换为十六进制字符串:

dechex(mt_rand(0, 0xFFFFFF));
Run Code Online (Sandbox Code Playgroud)
  1. 为什么它首先存储元素的位置而不是元素?

    从手册页:

    这样做是为了您可以选择随机键以及数组中的值.

  2. 为什么array_rand()绝不选择一个字母作为第一个元素,几乎从不作为第二个/第三个(99%的生成颜色看起来像11111a 12345c 123456)?

    array_rand使用rand(php_rand,在C源代码中).取决于您的系统,php_randrand,randomlrand48.rand是一个特别差的随机数发生器.


Tim*_*mur 5

应该以更简单的方式生成随机颜色:

printf('%02x%02x%02x',mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
Run Code Online (Sandbox Code Playgroud)

要么

printf('%06x',mt_rand(0,16777215));
Run Code Online (Sandbox Code Playgroud)

如果需要将颜色保存到变量,请使用sprintf而不是printf