如何通过仅接管与第一个数组具有相同键的第二个数组中的值来合并两个数组?
我想将两个数组相互合并:
$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');
而合并应包括 $filtered
的所有元素以及 $changed
中具有相应键的所有元素 < code>$filtered:
$merged = array(1 => 'a', 3 => 'c*');
array_merge($filtered, $changed)
会将 $changed
的附加键添加到 $filtered
中,如下所示出色地。所以它并不真正适合。
我知道我可以使用 $keys = array_intersect_key($filtered, $changed) 来获取两个数组中存在的键,这已经是工作的一半了。
但是我想知道是否有任何(本机)函数可以将 $changed
数组减少为具有由 array_intersect_key
指定的 $keys
的数组>?我知道我可以将 array_filter
与回调函数一起使用,并检查其中的 $keys
,但可能还有其他一些纯本机函数来仅从数组中提取那些元素可以指定按键吗?
我这么问是因为本机函数通常比带有回调的 array_filter 快得多。
I'd like to merge two arrays with each other:
$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');
Whereas the merge should include all elements of $filtered
and all those elements of $changed
that have a corresponding key in $filtered
:
$merged = array(1 => 'a', 3 => 'c*');
array_merge($filtered, $changed)
would add the additional keys of $changed
into $filtered
as well. So it does not really fit.
I know that I can use $keys = array_intersect_key($filtered, $changed)
to get the keys that exist in both arrays which is already half of the work.
However I'm wondering if there is any (native) function that can reduce the $changed
array into an array with the $keys
specified by array_intersect_key
? I know I can use array_filter
with a callback function and check against $keys
therein, but there is probably some other purely native function to extract only those elements from an array of which the keys can be specified?
I'm asking because the native functions are often much faster than array_filter
with a callback.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果我正确理解你的逻辑,这应该可以做到:
实施:
输出:
This should do it, if I'm understanding your logic correctly:
Implementation:
Output:
如果您希望第二个数组($b)成为指示如果那里只有键的模式,那么您也可以尝试这个
if you want the second array ($b) to be the pattern that indicates that if there is only the key there, then you could also try this
如果您的键是非数字键(您的键不是数字键,因此这不是您确切问题的解决方案),那么您可以使用此技术:
结果:
这有效,因为对于非数字键,
array_merge
覆盖现有键的值,并将$changed
中的键附加到新数组的末尾。因此,我们可以简单地丢弃合并数组末尾超过原始数组计数的任何键。由于这适用于同一问题但具有不同的密钥类型,我想我会提供它。
如果您将其与数字键一起使用,则结果只是带有重新索引键的原始数组(在本例中为
$filtered
)(IE 就像您使用array_values
)。If your keys are non-numeric (which yours are not, so this is not a solution to your exact question), then you can use this technique:
Result:
This works because for non-numeric keys,
array_merge
overwrites values for existing keys, and appends the keys in$changed
to the end of the new array. So we can simply discard any keys from the end of the merged array more than the count of the original array.Since this applies to the same question but with different key types I thought I'd provide it.
If you use this with numeric keys then the result is simply the original array (
$filtered
in this case) with re-indexed keys (IE as if you usedarray_values
).