美好的一天,我已经玩了一段时间了,似乎无法分析如何使用PHP或javascript来输出数组概率,如果有人设法解决这个问题,请提前感谢
例:
$arrayNms = [
["A", "B", "C"],
["Q", "P"],
["CC", "C3"]
];
/*
OUTPUT
A, Q, CC
A, Q, C3
A, P, CC
A, P, C3
B, Q, CC
B, Q, C3
B, P, CC
B, P, C3
C, Q, CC
C, Q, C3
C, P, CC
C, P, C3
*/
//this is what I got so far, but can't seem to output the desired values
$arr1 = [];
for ($i = count($arrayNms) - 1; $i >= 0; $i--) {
for ($j=0; $j < count($arrayNms[$i]); $j++) {
$prdName1 = $arrayNms[$i][$j];
if(array_key_exists(($i+1), $arrayNms)){
for ($k=0; $k < count($arrayNms[$i+1]); $k++) {
$prdName2 = $arrayNms[$i][$k];
print_r($prdName2.', '.$prdName1);
}
}
}
}
非常感谢你
最佳答案
这似乎是大多数教科书给学生学习递归函数的一种挑战。这样的事情将提供所需的输出,并且无论$arrayNms
中有多少个值数组(只要至少有一个数组)都可以使用:
function print_values($array, $index = 0, $base = "") {
// check if there's another array of values after this one
$is_last = !isset($array[$index + 1]);
// loop through all values in the given sub-array
foreach ($array[$index] as $value) {
if ($is_last) {
// if this is the last array of values, output the current value
echo $base . $value . PHP_EOL;
} else {
// otherwise, append this value to the base and process the next array
print_values($array, $index + 1, $base . $value . ", ");
}
}
}
$arrayNms = [
["A", "B", "C"],
["Q", "P"],
["CC", "C3"]
];
print_values($arrayNms);
输出:
A, Q, CC
A, Q, C3
A, P, CC
A, P, C3
B, Q, CC
B, Q, C3
B, P, CC
B, P, C3
C, Q, CC
C, Q, C3
C, P, CC
C, P, C3