有什么可以帮助我获得输出:
a:b a:c 广告 a:e b:c b:d b:e c:d c:e d:e a:b:c a:b:d a:b:e a:c:d a:c:e a:d:e b:c:d b:c:e b:d:e c:d:e A B C D a:b:c:e a:b:d:e a:c:d:e b:c:d:e a:b:c:d:e
数据数组$ n =数组(' a',' b',' c',' d',&#39 ; E&#39);
我尝试过的代码如下:
for($a=0;$a<count($n);$a++)
{
for($b=$a+1;$b<count($n);$b++)
{
echo $n[$a].' : '.$n[$b].'<br />';
}
}
for($a=0;$a<count($n);$a++)
{
for($b=$a+1;$b<count($n);$b++)
{
for($c=$b+1;$c<count($n);$c++)
{
echo $n[$a].' : '.$n[$b].' : '.$n[$c].'<br />';
}
}
}
for($a=0;$a<count($n);$a++)
{
for($b=$a+1;$b<count($n);$b++)
{
for($c=$b+1;$c<count($n);$c++)
{
for($d=$c+1;$d<count($n);$d++)
{
echo $n[$a].' : '.$n[$b].' : '.$n[$c].' : '.$n[$d].'<br />';
}
}
}
}
for($a=0;$a<count($n);$a++)
{
for($b=$a+1;$b<count($n);$b++)
{
for($c=$b+1;$c<count($n);$c++)
{
for($d=$c+1;$d<count($n);$d++)
{
for($e=$d+1;$e<count($n);$e++)
{
echo $n[$a].' : '.$n[$b].' : '.$n[$c].' : '.$n[$d].' : '.$n[$e].'<br />';
}
}
}
}
}
但我觉得代码太长了请帮忙简化,
感谢
答案 0 :(得分:0)
<?php
$n = array ('a', 'b', 'c', 'd', 'e');
function getPerm($array, $key)
{
foreach( $array as $arrkey=>$value )
{
if($arrkey != $key)
{
echo " $array[$key]:$array[$arrkey] ";
}
}
}
foreach($n as $key=>$value)
{
getPerm($n, $key);
}
?>
答案 1 :(得分:0)
试试这个:
<?php
function getCombinations($base,$n){
$baselen = count($base);
if($baselen == 0){
return;
}
if($n == 1){
$return = array();
foreach($base as $b){
$return[] = array($b);
}
return $return;
}else{
//get one level lower combinations
$oneLevelLower = getCombinations($base,$n-1);
//for every one level lower combinations add one element to them that the last element of a combination is preceeded by the element which follows it in base array if there is none, does not add
$newCombs = array();
foreach($oneLevelLower as $oll){
$lastEl = $oll[$n-2];
$found = false;
foreach($base as $key => $b){
if($b == $lastEl){
$found = true;
continue;
//last element found
}
if($found == true){
//add to combinations with last element
if($key < $baselen){
$tmp = $oll;
$newCombination = array_slice($tmp,0);
$newCombination[]=$b;
$newCombs[] = array_slice($newCombination,0);
}
}
}
}
}
return $newCombs;
}
echo "<pre>";
print_r(getCombinations(array('a','b','c','d','e'),2));
?>
答案 2 :(得分:0)
爪哇:
ArrayList<String> setProduct (ArrayList<String> a, ArrayList<String> b)
{
ArrayList<String> prod = new ArrayList<String>();
for (String s : a)
{
for (String t : b)
{
prod.add(s + ":" + t);
}
}
return prod;
}
PHP:
<?php
function setProduct($a, $b)
{
$arr = array();
foreach ($a as $s)
{
foreach ($b as $t)
{
$arr[] = $s . ":" . $t;
}
}
return $arr;
}
?>