首頁  >  文章  >  後端開發  >  數組中隨機顯示一個?

數組中隨機顯示一個?

WBOY
WBOY原創
2016-10-10 11:56:27900瀏覽

<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><?php
$arry = array('A','B','C','D');
$rand_key = array_rand($array, 1);
echo $array[$rand_key];
</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 tables anseudo udods comnecto sooo notl.

如果第二個參數為1或沒有時, 回傳的並不是數組, 而只是一個數字
<code class="php">    $result = array_rand($arry,2); // 是一个**数组** 如[1,2,3]
    $result = array_rand($arry,1); // 只是一个**数字** 如 1, 并不是[1]
</code>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn