Search code examples
phparraysreplacestring-comparison

Merging two arrays, overwriting first array value with second array value when leading substring is the same


I would like to merge two arrays containing a list of files plus their revision in brackets.

For example:

First array:

['A[1]', 'B[2]', 'C[2]', 'D[2]']

Second one:

['B[3]', 'C[4]', 'E[4]', 'F[2]', 'G[2]']

Like I said, I would be able to merge both arrays, but overwriting the first one by the data present in the second one where the letter/filenames collide.

I used this regex to only grab filenames (removing the revision number). I don't know if I am correct on this point:

/\[[^\)]+\]/

The result I am looking for would be this,

['A[1]', 'B[3]', 'C[4]', 'D[2]', 'E[4]', 'F[2]', 'G[2]']

I'm using PHP4 at the moment.


Solution

  • something like:

    function helper() {
      $result = array();
    
      foreach (func_get_args() as $fileList) {
        foreach ($fileList as $fileName) {
          list($file, $revision) = explode('[', $fileName, 2);
          $revision = trim($revision, ']');
          $result[$file] = !isset($result[$file]) ? $revision : max($result[$file], $revision);
        }
      }
    
      foreach ($result as $file => $revision) {
        $result[$file] = sprintf('%s[%s]', $file, $revision);
      }
    
      return array_values($result);
    }
    
    $a = array('A[1]', 'B[2]', 'C[2]', 'D[2]');
    $b = array('B[3]', 'C[4]', 'E[4]', 'F[2]', 'G[2]');
    
    print_r(helper($a, $b));
    

    demo: http://codepad.org/wUMMjGXC