Concatenate two arrays, overwrite the first array with the second

I would like to concatenate 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,

0 => B[3], 1 => C[4], 2 => E[4], 3 => F[2], 4 => G[2]

      

As I said, I could concatenate both arrays, but overwrite the first of the data presented in the second.

I used this regex only to grab filenames (remove revision number). I don't know if I'm correct about this):

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

      

The result I am looking for would be like 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, it's all about PHP.

+3


source to share


3 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

+4


source


One way is to map both arrays with

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 records 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 indices, you can call array_values

in the result. The code above requires PHP 5.3, but it should be easy to make it compatible with earlier versions. Another caveat is that it will only work if the filenames are unique in the array.

DEMO (PHP version 5.2)

Link: array_map

, strstr

, array_combine

,array_merge

+2


source


You can use the union operator:

$newArray = $arr1 + $arr2;

      

You are right, array_merge

will only work if your keys were strings. With the number keys, the second array will simply be added to the first, without overwriting duplicate keys.

0


source







All Articles