title: Finding cartesian product with PHP associative arrays
body: <p>Say that I have an array like the following:</p>
  
  <pre><code>Array
  (
      [arm] =&gt; Array
          (
              [0] =&gt; A
              [1] =&gt; B
              [2] =&gt; C
          )
      [gender] =&gt; Array
          (
              [0] =&gt; Female
              [1] =&gt; Male
          )
      [location] =&gt; Array
          (
              [0] =&gt; Vancouver
              [1] =&gt; Calgary
          )
  )
  </code></pre>
  
  <p>How can I find the cartesian product while preserving the keys of the outer associative array and using them in the inner ones? The result of the algorithm should be this:</p>
  
  <pre><code>Array
  (
      [0] =&gt; Array
          (
              [arm] =&gt; A
              [gender] =&gt; Female
              [location] =&gt; Vancouver
          )
  
      [1] =&gt; Array
          (
              [arm] =&gt; A
              [gender] =&gt; Female
              [location] =&gt; Calgary
          )
  
      [2] =&gt; Array
          (
              [arm] =&gt; A
              [gender] =&gt; Male
              [location] =&gt; Vancouver
          )
  
  ...etc.
  </code></pre>
  
  <p>I've looked up quite a number of cartesian product algorithms but I'm getting stuck on the specifics of how to preserve the associative keys. The current algorithm I am using gives numerical indices only:</p>
  
  <pre><code>    $result = array();
      foreach ($map as $a) {
          if (empty($result)) {
              $result = $a;
              continue;
          }
          $res = array();
          foreach ($result as $r) {
              foreach ($a as $v) {
                  $res[] = array_merge((array)$r, (array)$v);
              }
          }
          $result = $res;
      }
  
      print_r($result);
  </code></pre>
  
  <p>Any help would be appreciated.</p>