title: Combine array items based on partial array keys
body: <p>I have a given multidimensional array like:</p>
  
  <pre><code>$givenArray = [
      'one__111__' =&gt; [ 'more' =&gt; '000'],
      'one__111__xyz' =&gt; [ 'more' =&gt; '000'],
      'hey__121__' =&gt; [ 'more' =&gt; '000'],
      'hey__121__abc' =&gt; [ 'more' =&gt; '000'],
      'zzz__212__' =&gt; [ 'more' =&gt; '000'],
      'zzz__212__b' =&gt; [ 'more' =&gt; '000'],
      'abc__3__' =&gt; [ 'more' =&gt; '000'],
  ];
  </code></pre>
  
  <p>I need to map the pairs if they start with the same key name. So <code>one__111__</code> and <code>one__111__xyz</code> is a pair.</p>
  
  <p>The result should look like:</p>
  
  <pre><code>[
      ['one__111__'] =&gt; [
          [0] =&gt; ['one__111__' =&gt; ['more' =&gt; '000']],
          [1] =&gt; ['one__111__xyz' =&gt; ['more' =&gt; '000']]
      ],
      ['hey__121__'] =&gt;
          [0] =&gt; ['hey__121__' =&gt; ['more' =&gt; '000']],
          [1] =&gt; ['hey__121__abc' =&gt; ['more' =&gt; '000']]
      ]
      ['zzz__212__'] =&gt;
          [0] =&gt; ['zzz__212__' =&gt; ['more' =&gt; '000']],
          [1] =&gt; ['zzz__212__b' =&gt; ['more' =&gt; '000']]
      ]
      ['abc__3__'] =&gt;
          [0] =&gt; ['abc__3__' =&gt; ['more' =&gt; '000']]
      ]
  ]
  </code></pre>
  
  <p>This is what I have tried. I believe it's O(n2)</p>
  
  <pre><code>$result = [];
  
  foreach($givenArray as $key =&gt; $value) {
      foreach($result as $resultItemKey =&gt; $resultItemValue) {
          if(substr($key, 0, strlen($resultItemKey)) === $resultItemKey)  {
              $result[$resultItemKey][] = [$key =&gt; $value];
              continue 2;
          }
      }
      $result[$key][] = [$key =&gt; $value];
  }
  </code></pre>
  
  <p>I've searched for the array filter/reduce/map functions but couldn't find the "right" one. Which array function should be used? Like I guess I need an array function which iterates over every item and allows me to pass in the newly created array. Is there such function in PHP?</p>
  
  <p><a href="http://sandbox.onlinephpfunctions.com/code/822662364e33190e6c625f2f0fcd1bf308d093ac" rel="nofollow noreferrer">PHP sandbox code to play with</a></p>