2012-02-14 19 views
6

Estoy tratando de llegar a un algoritmo en PHP para obtener todas las combinaciones de una matriz anidada:Obtener todas las combinaciones de múltiples matrices anidadas

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 
       ) 

     ) 

) 

Así que sería obtener algo a cambio, como:

-rough, brillante, grande

-rough, brillante, Pequeño

-rough, brillante, Medio

-rough, brillante, muy grande

-smooth, brillante, grande

-smooth, brillante, Pequeño

-smooth, brillante, Medio

-smooth, brillante, muy grande

etc (debería ser 24 en este ejemplo)

he intentado a través de diversos ejemplos foreach y algunas func fundamental recursiva ción, pero parece que no llego rápido a ninguna parte. Si alguien pudiera dar un esquema básico de cómo resolver esto, estaría muy agradecido, ¡gracias!

+1

y cómo es exactamente su código (que idealmente se agregaría a la pregunta) ¿fallando? Porque a primera vista, un conjunto de 3 bucles anidados debe ser todo lo que se necesita para resolver su problema. – fvu

+1

No diría que las matrices están anidadas, necesariamente. Todos están contenidos en una matriz principal, pero no están anidados entre sí. Pero para crear un [producto cartesiano] (http://en.wikipedia.org/wiki/Cartesian_product) utilizándolos a todos, desea * loops * anidados. – JYelton

+0

posible duplicado de [Búsqueda de producto cartesiano con matrices asociativas de PHP] (http://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays) – deceze

Respuesta

8

que acabo de escribir esto, que funciona para matrices de cualquier longitud ..

<?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"; 
} 

edición: mejoró un poco su código ..

+0

Ah, y solo fyi, en Python harías esto: http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a -series-of-lists-in-python :) – redShadow

+0

¡Funciona bien, gracias! – wonza

0

Aquí es la fuerza bruta (el peor eficiencia) algoritmo en pseudo-PHP:

$array1 = $array[0]; 
$array2 = $array[1]; 
$array3 = $array[2]; 

$results = array(); 
for($i = 0; $i < count($array1); $i++) 
    for($j = 0; $j < count($array2); $j++) 
     for($k = 0; $k < count($array3); $k++) 
      $results[] = $array1[$i] . ',' . $array2[$j] . ',' . $array3[$k]; 
+0

Como acabo de comentar arriba, no es necesariamente solo 3 foreach's needed. Lo anterior puede tener cualquier cantidad de elementos adicionales, esto es dinámico, así que no puedo limitarlo a 3 anidados para/foreach – wonza

+0

Oh, mi error. Su título es engañoso, ya que dice específicamente 3 arreglos. – nickb

+0

ah, bastante bien. ¡Lo siento! – wonza

1

Tiempo para anidar algunas foreach!

<?php 
$array1 = array('rough', 'smooth', 'coarse'); 
$array2 = array('shiny', 'matte'); 
$array3 = array('very large', 'large', 'medium', 'small'); 

foreach($array1 as $i) 
    foreach($array2 as $j) 
     foreach($array3 as $k) 
      $output[] = "$i, $j, $k"; 

var_dump($output); 
/* ouput 
array 
    0 => string 'rough, shiny, very large' (length=24) 
    1 => string 'rough, shiny, large' (length=19) 
    2 => string 'rough, shiny, medium' (length=20) 
    3 => string 'rough, shiny, small' (length=19) 
    4 => string 'rough, matte, very large' (length=24) 
    5 => string 'rough, matte, large' (length=19) 
    6 => string 'rough, matte, medium' (length=20) 
    7 => string 'rough, matte, small' (length=19) 
    8 => string 'smooth, shiny, very large' (length=25) 
    9 => string 'smooth, shiny, large' (length=20) 
    10 => string 'smooth, shiny, medium' (length=21) 
    11 => string 'smooth, shiny, small' (length=20) 
    12 => string 'smooth, matte, very large' (length=25) 
    13 => string 'smooth, matte, large' (length=20) 
    14 => string 'smooth, matte, medium' (length=21) 
    15 => string 'smooth, matte, small' (length=20) 
    16 => string 'coarse, shiny, very large' (length=25) 
    17 => string 'coarse, shiny, large' (length=20) 
    18 => string 'coarse, shiny, medium' (length=21) 
    19 => string 'coarse, shiny, small' (length=20) 
    20 => string 'coarse, matte, very large' (length=25) 
    21 => string 'coarse, matte, large' (length=20) 
    22 => string 'coarse, matte, medium' (length=21) 
    23 => string 'coarse, matte, small' (length=20) 
*/ 
?> 
+0

gracias por proporcionar la salida que hizo que la respuesta sea fácil de validar – Ananda

Cuestiones relacionadas