php对数组内元素进行随机调换的方法_PHP教程

WBOY
Release: 2016-07-13 09:53:41
Original
922 people have browsed it

php对数组内元素进行随机调换的方法

   本文实例讲述了php对数组内元素进行随机调换的方法。分享给大家供大家参考。具体分析如下:

  这是一个自定义的php数组元素随机调换的函数,php已经有一个内置的同样功能的函数shuffle($Array),这个代码权当参考

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

// 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;

}

  使用范例:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

/*

** 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程序设计有所帮助。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1000104.htmlTechArticlephp对数组内元素进行随机调换的方法 本文实例讲述了php对数组内元素进行随机调换的方法。分享给大家供大家参考。具体分析如下: 这是...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!