Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Nested foreach on multi dimensional array

The following array gives me multiple "options" (type, purity, model). Keep in mind that "options" may increase or decrease on next iteration of the loop.

$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'),
);

The output I want to achieve is

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)

WHAT I HAVE ACHIEVED SO FAR.

If I have static "options" (type, purity, model) I can use nested foreach i.e

$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 />';

     }
   }
 }

But I don't know how many foreach loops should I use, as "options" may decrease or increase. So I have to dynamically go through the array. Any help will be much appreciated thanks

like image 948
Muhammad Asif Raza Avatar asked May 17 '26 02:05

Muhammad Asif Raza


1 Answers

$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 />";
}
like image 194
Matt Raines Avatar answered May 18 '26 18:05

Matt Raines



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!