title: PHP producing a multidimensional associative array in desired format
body: <p>I am trying to wrangle data into a desired format. Basically, I have a list in which a subset of the entities can have multiple values and need to be grouped and iterated over within the list. </p>
  
  <p>Given the following example:</p>
  
  <pre><code>$entities = [
      0 =&gt; ['name' =&gt; 'a', 'type' =&gt; 'single'],
      1 =&gt; ['name' =&gt; 'b', 'type' =&gt; 'single'],
      2 =&gt; ['name' =&gt; 'c', 'type' =&gt; 'grouped'],
      3 =&gt; ['name' =&gt; 'd', 'type' =&gt; 'grouped'],
      4 =&gt; ['name' =&gt; 'e', 'type' =&gt; 'single'],
  ];
  
  foreach ($entities as $entityKey =&gt; $entity) {
  
      if ($entity['type'] == 'single') {
  
          $array[] = ['name' =&gt; $entity['name']];
      }
  
      if ($entity['type'] == 'grouped') {
  
          // arbitrary number of items
          $items = [0 =&gt; 'apple', 1 =&gt; 'orange', 2 =&gt; 'banana'];
  
          foreach ($items as $itemKey =&gt; $item) {
              $array[] = ['name' =&gt; $entity['name']];
          }
      }
  }
  
  print_r($array);
  </code></pre>
  
  <p>How can I produce output: a, b, c, d, c, d, c, d, e, such that the entities of type 'grouped' are paired and iterated over before he next entity is inserted into the array. Specifically:</p>
  
  <pre><code>Array
  (
      [0] =&gt; Array
          (
              [name] =&gt; a
          )
  
      [1] =&gt; Array
          (
              [name] =&gt; b
          )
  
      [2] =&gt; Array
          (
              [name] =&gt; c
          )
  
      [3] =&gt; Array
          (
              [name] =&gt; d
          )
  
      [4] =&gt; Array
          (
              [name] =&gt; c
          )
  
      [5] =&gt; Array
          (
              [name] =&gt; d
          )
  
      [6] =&gt; Array
          (
              [name] =&gt; c
          )
  
      [7] =&gt; Array
          (
              [name] =&gt; d
          )
  
      [8] =&gt; Array
          (
              [name] =&gt; e
          )
  
  )
  </code></pre>