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
  • 308
  • 3
  • 18
  • 2
    Is it wanted that you don't use the "multidimensionnal side" of the arrays ? You only go through the first dimension keys in you loops. Btw, no need to make copies. – Jules R Jan 11 '19 at 12:20
  • 1
    you'd need to use a recursive function: https://stackoverflow.com/questions/2648968/what-in-laymans-terms-is-a-recursive-function-using-php –  Jan 11 '19 at 12:20
  • And can you provide a test array with the desired result ? – Jules R Jan 11 '19 at 12:21
  • @JulesR for two dimensions, would just be [1,1],[1,2],[2,1],[2,2]. for 3 there would be 9 combos – michael Jan 11 '19 at 12:39
  • 1
    @mattfryercom tried for hours. but no cigar – michael Jan 11 '19 at 12:40
  • Not sure about what you're doing, why aren't you using deeper keys ? – Jules R Jan 11 '19 at 12:49
  • @JulesR its complicated. let's just say this is the way it needs to be done. thanks – michael Jan 11 '19 at 12:53
  • I believe you can do array_keys and then use [this](https://www.geeksforgeeks.org/print-all-possible-combinations-of-r-elements-in-a-given-array-of-size-n/) – dWinder Jan 11 '19 at 13:09
  • @DavidWinder thanks but result needs to have n-elements each – michael Jan 11 '19 at 13:13
  • In that answer they have it (they just call it `r` and in their example its 3) – dWinder Jan 11 '19 at 13:50

1 Answers1

1

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
  • 553
  • 2
  • 18