這篇文章主要介紹了php對數組內元素進行隨機調換的方法,通過自定義函數實現對數組內元素進行隨機調換的功能,涉及php操作數組的相關技巧,需要的朋友可以參考下
本文實例講述了php對數組內元素進行隨機調換的方法。分享給大家供大家參考。具體分析如下:
這是一個自定義的php數組元素隨機調換的函數,php已經有一個內置的同樣功能的函數shuffle($Array),這個代碼權當參考
- // I noticed that there is already a built-in function that
- // does the same - so don't use mine ;-)
- //
- // --> shuffle($Array);
- //
- // http://de2.php.net/manual/de/function.shuffle.php
- //
- function RandomizeArray($array){
- // error check:
- $array = (!is_array($array)) ? array($array) : $array;
- $a = array();
- $max = count($array) + 10;
- while(count($array) > 0){
- $e = array_shift($array);
- $r = rand(0, $max);
- // find a empty key:
- while (isset($a[$r])){
- $r = rand(0, $max);
- }
- $a[$r] = $e;
- }
- ksort($a);
- $a = array_values($a);
- return $a;
- }
使用范例:
- /*
- ** Example:
- */
- $test_array = array('why','dont','visit','www','jonas','john','de',':-)');
- print implode(", ", $test_array);
- print "/n";
- print implode(", ", RandomizeArray($test_array));
- /*
- Example output:
- why, dont, visit, www, jonas, john, de, :-)
- www, de, jonas, john, visit, why, :-), dont
- */
希望本文所述對大家的php程序設計有所幫助。
新聞熱點
疑難解答