php求数组全排列,元素所有组合的方法总结

yipeiwu_com6年前PHP代码库

本文实例讲述了php求数组全排列,元素所有组合的方法总结。

分享给大家供大家参考,具体如下:

<?php
$source = array('pll','我','爱','你','嘿');
sort($source); //保证初始数组是有序的
$last = count($source) - 1; //$source尾部元素下标
$x = $last;
$count = 1; //组合个数统计
echo implode(',', $source), "<br>"; //输出第一种组合
while (true) {
 $y = $x--; //相邻的两个元素
 if ($source[$x] < $source[$y]) { //如果前一个元素的值小于后一个元素的值
  $z = $last;
  while ($source[$x] > $source[$z]) { //从尾部开始,找到第一个大于 $x 元素的值
   $z--;
  }
  /* 交换 $x 和 $z 元素的值 */
  list($source[$x], $source[$z]) = array($source[$z], $source[$x]);
  /* 将 $y 之后的元素全部逆向排列 */
  for ($i = $last; $i > $y; $i--, $y++) {
   list($source[$i], $source[$y]) = array($source[$y], $source[$i]);
  }
  echo implode(',', $source), "<br>"; //输出组合
  $x = $last;
  $count++;
 }
 if ($x == 0) { //全部组合完毕
  break;
 }
}
echo 'Total: ', $count, "\n";
?>

以上这篇php求数组全排列,元素所有组合的方法总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【宜配屋www.yipeiwu.com】。

相关文章

PHP动态生成指定大小随机图片的方法

本文实例讲述了PHP动态生成指定大小随机图片的方法。分享给大家供大家参考,具体如下: <?php $image_width = 100; $image_height =...

Thinkphp中import的几个用法详细介绍

下面附上import的几个用法介绍 1、用法一 import('@.Test.Translate'); @,表示项目根目录。假定根目录是:App/ 导入类库的路径是:App/Lib/Te...

PHPLog php 程序调试追踪工具

PHPLog php 程序调试追踪工具

原理:    1.程序执行的过程中,在相应的地方记录你想要追踪的变量及调用栈和每次函数调用的参数,        &...

在PHP中使用curl_init函数的说明

复制代码 代码如下: $ch = curl_init(); $c_url = 'http://www.baidu.com'; $c_url_data = "product_&type="...

php中file_get_contents()函数用法实例

我们先来看一下php中的 file_get_contents()函数的语法 string file_get_contents(string $ filename,bool $ inc...