在PHP中组合和排列两个不同数组的项



如何返回所有可能的组合[12345]、[12354]到[54312]、[54321]而不必运行120。。。循环,就像在下面的代码中组合一个2项数组的情况一样?

要从给定数组$word=[1,2]返回所有可能的组合,

//break the array into 2 separate arrays
$arr1 = $word[0]; $arr2 = $word[1];
//computer for first array item...each item will have 2 loops
for($i=0; $i<count($arr1); $i++){
for($j=0; $j<count($arr2); $j++){
$ret = $arr1[$i] . $arr2[$j]; array_push($result, $ret);
}
}
//computer for second array item..each item will have 2 loops
for($i=0; $i<count($arr2); $i++){
for($j=0; $j<count($arr1); $j++){
$ret = $arr2[$i] . $arr1[$j]; array_push($result, $ret);
}
}
//display the result
for ($i = 0; $i < count($result); $i++){
echo result([$i];
}

上面的代码运行良好。

但对于一个5项数组[1,2,3,4,5],它将需要大约(5项*24个循环(=120个循环。

如图所示,您想要拆分2 strings into chars并通过2 chars获得所有组合:第一个来自blank1,第二个来自blank2
不要手动进行组合,而是使用常规的for-loop

$result = array();
for ($i = 0; $i < count($blank1); $i++)
{
for ($j = 0; $j < count($blank2); $j++)
{
//set combination
$aux = $blank1[$i].$blank2[$j];
array_push($result, $aux);
}
}
//result should be populated with combination of 2
//just list it and use as need
for ($i = 0; $i < count($result); $i++)
{
echo $result[$i];
}
//same with stored or checking on db : use loops

对于多个组合,使用更多嵌套循环
例如:[blank1][blank2][blank1]-3组合

$result = array();
//1
for ($i = 0; $i < count($blank1); $i++)
{
//2
for ($j = 0; $j < count($blank2); $j++)
{
//3
for ($k = 0; $k < count($blank1); $k++)
{
//set combination
$aux = $blank1[$i].$blank2[$j].$blank1[$k];
array_push($result, $aux);
}
}
}


与您想要的任何号码相同!如果必须写很多循环,但要注意while can be used with an adequate algorithm,这会有点烦人。但就目前而言,只要尽可能简单,就能得到想要的结果。

最新更新