生成所有元素组合

时间:2012-06-07 01:50:43

标签: php arrays attributes combinations

我必须按唯一值和有序的方式生成元素的所有组合。 我用一个例子来解释,这些是参数及其值:

Dog : mal | female
Color : red | blue | yellow

the all combinations (ordered) to get are :
male - red
male - blue
male - yellow
female - red
female - blue
female - yellow

我怎样才能在php中使用数组?

提前致谢

1 个答案:

答案 0 :(得分:2)

$dogs = array( 'male', 'female');
$colors = array( 'red', 'blue', 'yellow');

foreach( $dogs as $dog)
    foreach( $colors as $color)
        echo $dog . ' - ' . $color . "\n";

<强>输出:

male - red
male - blue
male - yellow
female - red
female - blue
female - yellow

Demo