1

I am trying to expand/multiply an associative array N times and get all possible key combinations.

To do it manually for two times, I would do this:

  $copy = $array; 
  foreach ($array as $key1=>$tmp1) {  
   foreach ($copy as $key2=>$tmp2) {
    $combos[] = array($key1,$key2);
   }
  }

for expanding three times:

  $copy = $copy2 = $arr1;
  foreach ($arr1 as $key1=>$qd1) {  
   foreach ($copy as $key2=>$qd2) {
    foreach ($copy2 as $key3=>$qd3) {
     $combos[] = array($key1,$key2,$key3);
    }
   }
  }

how would one do this for n-times? $combos should have n-elements for each element as shown.

I looked at the other questions, but it is not quite the same here.

michael
  • 298
  • 2
  • 17

1 Answers1

2

Finally got it:

$array = ['1' => [3, 4], '2' => [5, 6]];
$depth = 2;

function florg ($n, $elems) {
    if ($n > 0) {
      $tmp_set = array();
      $res = florg($n-1, $elems);
      foreach ($res as $ce) {
          foreach ($elems as $e) {
             array_push($tmp_set, $ce . $e);
          }
       }
       return $tmp_set;
    }
    else {
        return array('');
    }
}

$output = florg($depth, array_keys($array));

What I did is basically extract the first level keys with array_keys and then created all possibles combinations thanks to https://stackoverflow.com/a/19067650/4585634.

Here's a working demo: http://sandbox.onlinephpfunctions.com/code/94c74e7e275118cf7c7f2b7fa018635773482fd5

Edit: didn't see David Winder comment, but that's basically the idea.

Jules R
  • 563
  • 2
  • 18