Php 数组数据的组合
是否有任何东西可以帮助我获得以下输出: a:b a:c a:d 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','e') 我试过这样的代码:Php 数组数据的组合,php,algorithm,Php,Algorithm,是否有任何东西可以帮助我获得以下输出: a:b a:c a:d 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','e') 我试过这样的代码: for($a=0;$a<count($n);$a++) { fo
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 />';
}
}
}
}
}
($a=0;$a
请参见代码板尝试以下操作:
<?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));
?>
参考:Java:
<?php
function setProduct($a, $b)
{
$arr = array();
foreach ($a as $s)
{
foreach ($b as $t)
{
$arr[] = $s . ":" . $t;
}
}
return $arr;
}
?>
ArrayList集合产品(ArrayList a、ArrayList b)
{
ArrayList prod=新的ArrayList();
for(字符串s:a)
{
for(字符串t:b)
{
产品添加(s+“:”+t);
}
}
返回产品;
}
PHP:
使用递归函数。相反,我希望输出为:ab,ac,ad,ae,bc,bd,be,cd,de,ab c,ab d,ab e,cd,ac d,ac e,ad,de,bd,bd,bd,bd,bd,bd,bd,bd,de,bd,de,bd,de,bd,好的,谢谢Prasanth Bendra
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
function setProduct($a, $b)
{
$arr = array();
foreach ($a as $s)
{
foreach ($b as $t)
{
$arr[] = $s . ":" . $t;
}
}
return $arr;
}
?>