Heim  >  Artikel  >  Backend-Entwicklung  >  數組中隨機顯示一個?

數組中隨機顯示一個?

WBOY
WBOYOriginal
2016-10-10 11:56:27900Durchsuche

<code> $arry = array('A','B','C','D');
$result = array_rand($arry,2);
foreach ($result as $val) 
{
echo $arry["$val"].""; 
}
</code>

請問一下 這樣會隨機產生2組 ABCD的組合 例如BC DC AB等等
但我想顯示的是只要顯示一個就好了 隨機從數組中顯示A或B或C或D
請問這樣怎麼做?
我把2改1後就失敗了

回复内容:

<code> $arry = array('A','B','C','D');
$result = array_rand($arry,2);
foreach ($result as $val) 
{
echo $arry["$val"].""; 
}
</code>

請問一下 這樣會隨機產生2組 ABCD的組合 例如BC DC AB等等
但我想顯示的是只要顯示一個就好了 隨機從數組中顯示A或B或C或D
請問這樣怎麼做?
我把2改1後就失敗了

<code>
mixed array_rand ( array $array [, int $num = 1 ] )
# Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. It uses a pseudo random number generator that is not suitable for cryptographic purposes.
</code>

会随机返回指定数组中的键,根据需求$num会返回一个键 或 以数组的形式返回多个键。

如果你有数组

<code><?php $arry = array('A','B','C','D');
</code></code>

现在想每次随机输出数组中的一个元素,则可以采用以下方式获取:

<code><?php $arry = array('A','B','C','D');
$rand_key = array_rand($array, 1);
echo $array[$rand_key];
</code></code>

以此同理可以实现其他的随机元素键并获取数组的随机元素。

<code class="php">$array = array('A','B','C','D');
$newArray = $array;
shuffle($newArray);
echo $newArray[0];
</code>

Picks one or more random entries out of an array, and returns the key
(or keys) of the random entries. It uses a pseudo random number
generator that is not suitable for cryptographic purposes.

如果第二个参数为1或者没有时, 返回的并不是数组, 而只是一个数字

<code class="php">    $result = array_rand($arry,2); // 是一个**数组** 如[1,2,3]
    $result = array_rand($arry,1); // 只是一个**数字** 如 1, 并不是[1]
</code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn