Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all combinations from multiple nested arrays

I'm trying to come up with an algorithm in PHP to get all the combinations for a nested array:

Array
(
    [0] => Array
        (
            [0] => Option Object
                (
                    [strValue] => rough
                )

            [1] => Option Object
                (
                    [strValue] => smooth
                )

            [2] => Option Object
                (
                    [strValue] => coarse
                )

        )

    [1] => Array
        (
            [0] => Option Object
                (
                    [strValue] => shiney
                )

            [1] => Option Object
                (
                    [strValue] => mat
                )

        )

    [2] => Array
        (
            [0] => Option Object
                (
                    [strValue] => Large
                )

            [1] => Option Object
                (
                    [strValue] => Medium
                )

            [2] => Option Object
                (
                    [strValue] => Small
                )

            [3] => Option Object
                (
                    [strValue] => very large
                )

        )

)

So I would get something back like:

-rough, shiney, Large

-rough, shiney, Small

-rough, shiney, Medium

-rough, shiney, Very Large

-smooth, shiney, Large

-smooth, shiney, Small

-smooth, shiney, Medium

-smooth, shiney, Very Large

etc (should be 24 in this example)

I've tried through various foreach examples and some basic recursive function, but I seem to be getting no where fast. If anyone could give a basic outline of how to solve this I'd be very grateful, thanks!

like image 952
wonza Avatar asked Feb 14 '12 00:02

wonza


1 Answers

I just wrote this, that works for arrays of any length..

<?php

function cartesian_product($a) {
  $result = array(array());
  foreach ($a as $list) {
    $_tmp = array();
    foreach ($result as $result_item) {
      foreach ($list as $list_item) {
        $_tmp[] = array_merge($result_item, array($list_item));
      }
    }
    $result = $_tmp;
  }
  return $result;
}


// Let's test this..                                                                                                                                                                                    

header('Content-type: text/plain');

$a = array(
  array('rough','smooth','coarse'),
  array('shiney','mat'),
  array('small','medium','large','x-large'),
);

$result = cartesian_product($a);
foreach ($result as $row) {
  print implode(", ", $row) ."\n";
}

edit: Improved the code a bit..

like image 128
redShadow Avatar answered Nov 14 '22 23:11

redShadow