本文目录一览:
- 1、PHP 多个数组的排列组合
- 2、求PHP 数组的任意组合的算法函数
- 3、php 如何计算数组中数字的组合?
- 4、php 多组数字如何计算所有的组合形式。如:
- 5、PHP中如何列出一个数组的所有规定组合?
PHP 多个数组的排列组合
$a = array(1,2,3,4,5,6,7);
$b = array(1,2,3);
$c = array(1,2,3,4,5,6,7,8,9,10);
$d = array($a,$b,$c);
//计算每一个数组的长度
$len = 1;
$arrLen = count($d); //需要排列数组有多少个
$recIndex = null; //记录当前该取的位置
//foreach 计数
$count_3 = 0;
foreach ($d as $key = $value) {
$lenRec[$count_3] = count($value);
$len = $lenRec[$count_3]*$len;
$recIndex[] = 0;//第一次全部取第0个
$count_3++;
}
//算出% 的值
$count = 1;
foreach ($lenRec as $key = $value) {
$moduloVal = 1;
if($arrLen == $count){
$modulo[] = count($d[$arrLen-1]); //等于最后一个的长度
}else{
$count_1 = 1;
foreach ($lenRec as $index = $item) {
$count_1 $count $moduloVal = $moduloVal*$item;
$count_1 ++;
}
$modulo[] = $moduloVal;
}
$count ++;//为了防止$d key是有值的 不是自然序列 需要计数
}
$i = 1;
while ( $i = $len) {
$html = '';
$count_2 = 0;// 取模
$temp = '';
foreach ($d as $value) {
$html .= $value[$recIndex[$count_2]%$lenRec[$count_2]].",";
$count_2 ++;
}
echo $html."br";
foreach ($modulo as $key = $value) {
if($i%$value == 0 $key $arrLen - 1 ){
$recIndex[$key] = $recIndex[$key] +1;
}
if($key == $arrLen - 1){
if($i%$value == 0){
$recIndex[$key] = 0;
}else{
$recIndex[$key] = $recIndex[$key] +1;
}
}
}
$i ++;
//改变获取的位置
}
求PHP 数组的任意组合的算法函数
function getRank($arr, $len=0, $str="") {
global $arr_getrank;
$arr_len = count($arr);
if($len == 0){
$arr_getrank[] = $str;
}else{
for($i=0; $i$arr_len; $i++){
$tmp = array_shift($arr);
if (empty($str))
{
getRank($arr, $len-1, $tmp);
}
else
{
getRank($arr, $len-1, $str.",".$tmp);
}
// array_push($arr, $tmp);
}
}
}
测试:
$words = array('a1','b2','c3','d4','e5');
$arr_getrank = array();
getRank($words, 3);
print_r($arr_getrank);
输出:
Array
(
[0] = a1,b2,c3
[1] = a1,b2,d4
[2] = a1,b2,e5
[3] = a1,c3,d4
[4] = a1,c3,e5
[5] = a1,d4,e5
[6] = b2,c3,d4
[7] = b2,c3,e5
[8] = b2,d4,e5
[9] = c3,d4,e5
)
php 如何计算数组中数字的组合?
$arr = array(1,2,2,3,3,3,4,5,3,2,3,3);$num = count(array_count_values($arr));// 或者$num = count(array_unique($arr));
php 多组数字如何计算所有的组合形式。如:
$A = ['红色','黄色'];
$B = ['M','L','XL'];
$C = ['轻','重'];
// 先将各属性值处理成一个整体
$list['A'] = $A;
$list['B'] = $B;
$list['C'] = $C;
$res = array();
foreach ($list as $k = $v) {
$res = getCombinationToString($v);
}
/**
* 获取组合的结果
* [@author]() 18y
*/
function getCombinationToString($val){
// 保存上一个的值
static $res = array();
if(empty($res))
{
$res = $val;
}else{
// 临时数组保存结合的结果
$list = array();
foreach ($res as $k = $v) {
foreach ($val as $key = $value) {
$list[$k.'_'.$key] = $v.'_'.$value;
}
}
$res = $list;
}
return $res;
}
详情看全文吧,这里写有点乱 php 多组数组算所有的组合形式
PHP中如何列出一个数组的所有规定组合?
嵌套循环,代码如下:
$arr = array('0'=array(8,9),'1'=array(5),'2'=array(1,2));
$arr2 = array();
foreach ($arr[0] as $v1) {
foreach($arr[1] as $v2){
foreach($arr[2] as $v3){
$arr2[] = $v1.$v2.$v3;
}
}
}
print_r($arr2);