Home > Backend Development > PHP Tutorial > php对数组内元素进行随机调换的方法_php技巧

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

WBOY
Release: 2016-05-16 20:16:01
Original
1026 people have browsed it

本文实例讲述了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;
}
Copy after login

使用范例:

/*
** 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
*/
Copy after login

希望本文所述对大家的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