Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two arrays, overwriting first array with second one

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

For example:

Fist array:

0 => A[1], 1 => B[2], 2 => C[2], 3 => D[2]

Second one,

0 => B[3], 1 => C[4], 2 => E[4], 3 => F[2], 4 => 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.

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,

0 => A[1], 1 => B[3], 2 => C[4], 3 => D[2], 4 => E[4], 5 => F[2], 6 => G[2]

Also, I was about to forget, the whole thing is in PHP.

like image 307
Pierre-Olivier Avatar asked Mar 14 '12 17:03

Pierre-Olivier


2 Answers

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

like image 185
Yoshi Avatar answered Oct 01 '22 10:10

Yoshi


One way would be to map both arrays to

filename => filename[revision]

such that

Array
(
    [0] => A[1]
    [1] => B[2]
    [2] => C[2]
    [3] => D[2]
)

becomes

Array
(
    [A] => A[1]
    [B] => B[2]
    [C] => C[2]
    [D] => D[2]
)

and then use array_merge (which overrides entries with the same key).

Something like:

function map($array) {
    $filenames = array_map(function($value) {
        return strstr($value, '[', false);
    }, $array);
    return array_combine($filenames, $array);
}

$result = array_merge(map($array1), map($array2));

If you want to have numeric indexes, you can call array_values on the result. The code above requires PHP 5.3 but it should be easy to make it compatible with earlier versions. The other caveat is that it would only work if filenames are unique in the array.

DEMO (PHP 5.2 version)

Reference: array_map, strstr, array_combine, array_merge

like image 23
Felix Kling Avatar answered Oct 01 '22 12:10

Felix Kling