PHP Nested foreach on multi dimensional array

Muhammad Asif Raza

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Can't pass Multi-Dimensional array to foreach function - PHP

php - Getting Data from multi dimensional array (foreach)

PHP create multi dimensional array

Multi dimensional php array not working

modifying multi dimensional array in PHP

PHP Search Multi Dimensional Array

Sort multi dimensional array in php

Convert Multi dimensional array PHP

Multi dimensional associative array in php

How to make a multi dimensional array in a foreach loop

Print multi-dimensional array using foreach

store foreach results in multi dimensional array

foreach loop inside multi-dimensional array

Could not send nested multi dimensional json object POST request in PHP because multi dimensional json corrupted when converting it to array

Consolidate single multi-dimensional array by individual key of nested array PHP

PHP array with a nested foreach

PHP array unique on multi dimensional array/object

how to multiply array in multi dimensional array in php

Split Multi Dimensional array into single array :PHP

How to convert multi dimensional array to single dimensional array in php ?

multi-dimensional javascript array only affecting last array in forEach

Multi-Dimensional Array if array elements are missing in foreach

Empty currently filled multi dimensional array in PHP

Convert a json to multi-dimensional PHP array

PHP remove value from multi dimensional array

How to parse a multi dimensional array to PHP

PHP Multi Dimensional Array's Value?

How to convert multi dimensional json to php array?

Generate multi dimensional PHP array using range

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive