您可以使用 foreach 循环轻松实现此目的:
$array1 = array('100GB', '500GB');
$array2 = array('black', 'yellow', 'green');
$array3 = array('2.5');
$combinations = array();
foreach ($array1 as $i) {
foreach ($array2 as $j) {
foreach ($array3 as $k) {
$combinations[] = $i.' - '.$j.' - '.$k;
}
}
}
echo implode("\n", $combinations);
Edit:要处理空数组,您可以使用此函数:
function combinations($arrays, $i = 0) {
if (!isset($arrays[$i])) {
return array();
}
if ($i == count($arrays) - 1) {
return $arrays[$i];
}
// get combinations from subsequent arrays
$tmp = combinations($arrays, $i + 1);
$result = array();
// concat each array from tmp with each element from $arrays[$i]
foreach ($arrays[$i] as $v) {
foreach ($tmp as $t) {
$result[] = is_array($t) ?
array_merge(array($v), $t) :
array($v, $t);
}
}
return $result;
}
该函数取自this https://stackoverflow.com/a/8567199答案,所以功劳归于作者。然后你可以调用这个combinations
这样运行:
$array1 = array('100GB', '500GB');
$array2 = array();
$array3 = array('2.5');
$arrays = array_values(array_filter(array($array1, $array2, $array3)));
$combinations = combinations($arrays);
foreach ($combinations as &$combination) {
$combination = implode(' - ', $combination);
}
echo implode("\n", $combinations);
这输出:
100GB - 2.5
500GB - 2.5