下面的数组给了我多个"选项"(类型、纯度、型号)。请记住,"选项"可能会在循环的下一次迭代中增加或减少。
$options = array(
'type' => array('Old', 'Latest', 'GOLD 1.0', 'GOLD 1.1', 'GOLD 1.2', 'GOLD 1.3'),
'purity' => array('GOLD', 'SILVER', 'BRONZE'),
'model' => array('Rough', 'Neat', 'mixed', 'Random'),
);
我想要实现的输出是
Old GOLD Rough
Old GOLD Neat
Old GOLD mixed
Old GOLD Random
Old SILVER Rough
Old SILVER Neat
Old SILVER mixed
Old SILVER Random
Old BRONZE Rough
Old BRONZE Neat
Old BRONZE mixed
Old BRONZE Random
Then this whole scenario goes for 'Latest', 'GOLD 1.0', 'GOLD 1.1',
'GOLD 1.2' and 'GOLD 1.3'(each element of first array)
This way it will generate total 72 combinations (6 * 3 * 4)
到目前为止,我所取得的成就。
如果我有静态"选项"(类型、纯度、型号),我可以为每个使用嵌套,即
$type = array('Old', 'Latest', 'GOLD 1.0', 'GOLD 1.1', 'GOLD 1.2', 'GOLD 1.3');
$purity = array('GOLD', 'SILVER', 'BRONZE');
$model = array('Rough', 'Neat', 'mixed', 'Random');
foreach( $type as $base ){
foreach( $purity as $pure ){
foreach( $model as $mdl ){
echo $base.' '.$pure.' '.$mdl.'<br />';
}
}
}
但我不知道我应该使用多少个 foreach 循环,因为"选项"可能会减少或增加。所以我必须动态地遍历数组。任何帮助将不胜感激谢谢
$options = array(
'type' => array('Old', 'Latest', 'GOLD 1.0', 'GOLD 1.1', 'GOLD 1.2', 'GOLD 1.3'),
'purity' => array('GOLD', 'SILVER', 'BRONZE'),
'model' => array('Rough', 'Neat', 'mixed', 'Random'),
);
// Create an array to store the permutations.
$results = array();
foreach ($options as $values) {
// Loop over the available sets of options.
if (count($results) == 0) {
// If this is the first set, the values form our initial results.
$results = $values;
} else {
// Otherwise append each of the values onto each of our existing results.
$new_results = array();
foreach ($results as $result) {
foreach ($values as $value) {
$new_results[] = "$result $value";
}
}
$results = $new_results;
}
}
// Now output the results.
foreach ($results as $result) {
echo "$result<br />";
}