PHP中如何在數組中隨機抽取n個數據的值?
最佳答案
array_rand() 在你想從數組中取出一個或多個隨機的單元時相當有用。它接受 input 作為輸入數組和一個可選的參數 num_req,指明了你想取出多少個單元 - 如果沒有指定,默認為 1。如果你只取出一個,array_rand() 返回一個隨機單元的鍵名,否則就返回一個包含隨機鍵名的數組。這樣你就可以隨機從數組中取出鍵名和值。
如下例所示:
<?php $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";
輸出:
Trinity Cypher
【注意】
當 num_req 為 1 時,返回非數組數據,而當 num_req >=2 時,返回數組數據,所以,如果取的數量不確定是否為 1 的情況下,建議如下方式統一轉換為數組:
$num_req = max(1, $num_req); $num_req = min($num_req, count($input)); $rand_keys = (array)array_rand($input, $num_req);