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

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

相关文章

PHP中Memcache操作类及用法实例

本文实例讲述了PHP中Memcache操作类及用法。分享给大家供大家参考。具体分析如下: 复制代码 代码如下: <?php     ...

php实现转换ubb代码的方法

本文实例讲述了php实现转换ubb代码的方法。分享给大家供大家参考。具体如下: function ubb2html($content) { global $article; //是否...

PHP中使用CURL伪造来路抓取页面或文件

复制代码 代码如下: // 初始化 $curl = curl_init(); // 要访问的网址 curl_setopt($curl, CURLOPT_URL, 'http://asen...

PHP实现的数独求解问题示例

本文实例讲述了PHP实现的数独求解问题。分享给大家供大家参考,具体如下: 一、数独问题描述: 对于给出的数字二维数组,要求每行每列的数字不能重复。 二、实现代码: <?...

PHP设计模式之PHP迭代器模式讲解

PHP设计模式之PHP迭代器模式讲解

迭代器有时又称光标(cursor)是程式设计的软件设计模式,可在容器物件(container,例如list或vector)上遍访的接口,设计人员无需关心容器物件的内容。 各种语言实作It...