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

yipeiwu_com5年前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 callback函数使用方法和注意事项

在PHP中有些诸如 call_user_function() 或 usort() 的函数接受用户自定义的函数作为一个参数。Callback 函数不仅可以是一个简单的函数,它还可以是一个对...

从PHP的源码中深入了解stdClass类

在百度百科中,对于stdClass的定义如下:复制代码 代码如下:stdClass在PHP5才开始被流行。而stdClass也是zend的一个保留类。stdClass是PHP的一个基类,...

linux下 C语言对 php 扩展

一,搭建php环境下载php 5.2.6 源码 并解压编译安装,搭建php环境二,创建扩展项目进入源码目录cd php5.2.6/ext/./ext_skel --extname=my_...

php下使用无限生命期Session的方法

在PHP4.0中加入了对Session的支持,方便了我们很多程序,比如购物车等等!    在很多论坛中,Session也用于处理用户的登陆,记录下用户名和密码,使得用户不必每次...

PHP中文分词的简单实现代码分享

当然, 本文不是要对中文搜索引擎做研究, 而是分享如果用 PHP 做一个站内搜索引擎。 本文是这个系统中的一篇。 我使用的分词工具是中科院计算所的开源版本的 ICTCLAS。 另外还有开...