PHP嵌套的foreach在多维数组

时间:2016-03-02 13:03:38

标签: php arrays multidimensional-array foreach nested

以下数组为我提供了多个"选项" (类型,纯度,型号)。请记住"选项"可能会在循环的下一次迭代中增加或减少。

$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)

我实现了什么。

如果我有静态"选项" (类型,纯度,型号)我可以使用嵌套的foreach,即

$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循环,因为&#34;选项&#34;可能减少或增加。所以我必须动态浏览数组。任何帮助都感激不尽 感谢

1 个答案:

答案 0 :(得分:1)

$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 />";
}