从php中的两个数组生成所有组合

我有两个这样的数组:


$a = array("abc","defs","ghi");

$b = array("abcs","def","ghis");

我想要像这样的字符串的所有组合:


abc defs ghi

abc def ghi

abc def ghis

abc defs ghis

abcs defs ghi

abcs def ghi

abcs def ghis

abcs defs ghis

如何在 php 中做到这一点?


PS - 数组可以是任意长度,但两个数组的大小始终相同。


PPS - 在这个问题中给出的公认答案没有给我正确的结果。它给出了以下结果:


Array ( [0] => Array ( [0] => abc [1] => abcs ) [1] => Array ( [0] => abc [1] => def ) [2] => Array ( [0] => abc [1] => ghi ) [3] => Array ( [0] => defs [1] => abcs ) [4] => Array ( [0] => defs [1] => def ) [5] => Array ( [0] => defs [1] => ghi ) [6] => Array ( [0] => ghi [1] => abcs ) [7] => Array ( [0] => ghi [1] => def ) [8] => Array ( [0] => ghi [1] => ghi ) ) 


慕的地10843
浏览 247回答 1
1回答

HUH函数

你需要将你的数组转换成这个,$a&nbsp; &nbsp; = ["abc", "defs", "ghi"];$b&nbsp; &nbsp; = ["abcs", "def", "ghis"];$temp = array_map(null, $a, $b); // this conversion we call it transposing of arrayfunction combinations($arrays){&nbsp; &nbsp; $result = [];&nbsp; &nbsp; $arrays = array_values($arrays);&nbsp; &nbsp; $sizeIn = sizeof($arrays);&nbsp; &nbsp; $size&nbsp; &nbsp;= $sizeIn > 0 ? 1 : 0;&nbsp; &nbsp; foreach ($arrays as $array) {&nbsp; &nbsp; &nbsp; &nbsp; $size = $size * sizeof($array);&nbsp; &nbsp; }&nbsp; &nbsp; for ($i = 0; $i < $size; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; $result[$i] = [];&nbsp; &nbsp; &nbsp; &nbsp; for ($j = 0; $j < $sizeIn; $j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array_push($result[$i], current($arrays[$j]));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for ($j = ($sizeIn - 1); $j >= 0; $j--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (next($arrays[$j])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } elseif (isset($arrays[$j])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; reset($arrays[$j]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return $result;}$res = combinations($temp);// imploding all the values internally with space$temp = array_map(function($item){&nbsp; &nbsp; return implode(" ", $item);},$res);// looping to show the dataforeach($temp as $val){&nbsp; &nbsp; echo $val."\n";}使用 array_map 转换数组后,我使用了this 的帮助。演示。输出abc defs ghiabc defs ghisabc def ghiabc def ghisabcs defs ghiabcs defs ghisabcs def ghiabcs def ghis
打开App,查看更多内容
随时随地看视频慕课网APP