php 陣列隨機取值的簡單例項

2021-08-20 10:56:28 字數 2334 閱讀 1054

array_rand() 在你想從陣列中取出乙個或多個隨機的單元時相當有用。它接受 input 作為輸入陣列和乙個可選的引數 num_req,指明了你想取出多少個單元 - 如果沒有指定,預設為 1。

array_rand -- 從陣列中隨機取出乙個或多個單元

mixed array_rand ( array input [, int num_req])
array_rand() 在你想從陣列中取出乙個或多個隨機的單元時相當有用。它接受 input 作為輸入陣列和乙個可選的引數 num_req,指明了你想取出多少個單元 - 如果沒有指定,預設為 1。

如果你只取出乙個,array_rand() 返回乙個隨機單元的鍵名,否則就返回乙個包含隨機鍵名的陣列。這樣你就可以隨機從陣列中取出鍵名和值。

不要忘記呼叫 srand() 來撒下隨機數發生器的種子。

例子 1. array_rand() 例子

srand ((float) microtime() * 10000000);  $input = array ("neo", "morpheus", "trinity", "cypher", "tank");  $rand_keys = array_rand ($input, 2);  print $input[$rand_keys[0]]."\n";  print $input[$rand_keys[1]]."\n";
步驟

程式實現的原理是:呼叫乙個陣列,每個圖象對應乙個陣列中的元素,然後我們設定隨機數,只要隨機得到乙個資料就可以顯示一副圖象了。

第乙個步是我們來產生乙個隨機數。每次重新整理時我們都得到不同的隨機數,具體**為:

srand((float) microtime() * 10000000);
之後我們設定乙個陣列為image,然後再設定5個陣列元素,**如下:

$image[1]='/location/of/image1.jpg';  $image[2]='/location/of/image2.jpg';  $image[3]='/location/of/image3.jpg';  $image[4]='/location/of/image4.jpg';  $image[5]='/location/of/image5.jpg';
下面的**實現的功能是從陣列中隨機選擇乙個元素:

$rn = array_rand($image);
然後我們來顯示乙個隨機的:

echo '
把上面的**組合起來就可以了。

srand((float) microtime() * 10000000);  $image[1]='/location/of/image1.jpg';  $image[2]='/location/of/image2.jpg';  $image[3]='/location/of/image3.jpg';  $image[4]='/location/of/image4.jpg';  $image[5]='/location/of/image5.jpg';  $rn = array_rand($image);  echo '
$image[1]['pic']='/location/of/image1.jpg';  $image[1]['link']='/location/of/link1.php';
相應的顯示**為:

php 陣列定義 取值和遍歷

常用函式 生成隨機數 echo rand 1,10 兩個引數來確定隨機數的範圍 日期時間函式 var dump time 取當前時間的unix時間戳 date default timezone set prc echo date y m d h i s time 格式化日期時間戳 echo date...

PHP 定義陣列,取值陣列和遍歷陣列

php陣列 特點 可以儲存任意型別的資料,可以不連續,可以是索引的也可以是關聯的 什麼是索引?就是常見陣列的樣式,索引從開始,0,1,2,3,定義陣列是直接往裡面放值,只個索引自動生成,所以一般從0開始的,這樣的陣列是索引陣列,索引是連續的。什麼是關聯?就是我們的雜湊表集合,在定義的時候,必須給它乙...

php 隨機獲取陣列 的方法

今天網上搜到的方法,很好的解決了我的問題,記錄一下 方法1 arr array 初始化陣列 key array rand arr 隨機獲取陣列的鍵 echo arr key 輸出隨機數組值。改進型 arr array echo arr array rand arr 方法2 arr array 初始化...