[英]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. 此外,我即将忘记,整个事情是在PHP。
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 演示: http : //codepad.org/wUMMjGXC
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). 然后使用array_merge
(它覆盖具有相同键的条目)。
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. 如果要使用数字索引,可以在结果上调用array_values
。 The code above requires PHP 5.3 but it should be easy to make it compatible with earlier versions. 上面的代码需要PHP 5.3,但它应该很容易使它与早期版本兼容。 The other caveat is that it would only work if filenames are unique in the array. 另一个需要注意的是,只有文件名在数组中是唯一的时才会起作用。
DEMO (PHP 5.2 version) 演示 (PHP 5.2版)
Reference: array_map
, strstr
, array_combine
, array_merge
参考: array_map
, strstr
, array_combine
, array_merge
You could use the union operator : 你可以使用union运算符 :
$newArray = $arr1 + $arr2;
You are right, array_merge
would only work if your keys were strings. 你说得对, array_merge
只有你的键是字符串才能工作。 With numeric keys, the second array will just be appended to the first, without overwriting duplicate keys. 使用数字键,第二个数组将仅附加到第一个数组,而不会覆盖重复键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.