問(wèn)題描述
我想合并兩個(gè)數(shù)組:
$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');
而合并應(yīng)包括 $filtered
的所有元素和 $changed
的所有元素,這些元素在 $filtered
中有相應(yīng)的鍵:
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)
也會(huì)將 $changed
的附加鍵添加到 $filtered
中.所以不太合適.
array_merge($filtered, $changed)
would add the additional keys of $changed
into $filtered
as well. So it does not really fit.
我知道我可以使用 $keys = array_intersect_key($filtered, $changed)
來(lái)獲取兩個(gè)數(shù)組中存在的鍵,這已經(jīng)完成了一半的工作.
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.
但是我想知道是否有任何(本機(jī))函數(shù)可以將 $changed
數(shù)組減少為具有 array_intersect_key 指定的
$keys
的數(shù)組代碼>?我知道我可以使用帶有回調(diào)函數(shù)的 array_filter
并檢查其中的 $keys
,但可能還有其他一些純本機(jī)函數(shù)來(lái)僅從數(shù)組中提取那些元素可以指定鍵嗎?
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?
我這么問(wèn)是因?yàn)樵瘮?shù)通常比帶有回調(diào)的 array_filter
快得多.
I'm asking because the native functions are often much faster than array_filter
with a callback.
推薦答案
如果我正確理解你的邏輯,應(yīng)該這樣做:
This should do it, if I'm understanding your logic correctly:
array_intersect_key($changed, $filtered) + $filtered
<小時(shí)>
實(shí)施:
$filtered = array(1 => 'a', 3 => 'c');
$changed = array(2 => 'b*', 3 => 'c*');
$expected = array(1 => 'a', 3 => 'c*');
$actual = array_key_merge_deceze($filtered, $changed);
var_dump($expected, $actual);
function array_key_merge_deceze($filtered, $changed) {
$merged = array_intersect_key($changed, $filtered) + $filtered;
ksort($merged);
return $merged;
}
輸出:
Expected:
array(2) {
[1]=>
string(1) "a"
[3]=>
string(2) "c*"
}
Actual:
array(2) {
[1]=>
string(1) "a"
[3]=>
string(2) "c*"
}
這篇關(guān)于如何通過(guò)僅從與第一個(gè)數(shù)組具有相同鍵的第二個(gè)數(shù)組中接管值來(lái)合并兩個(gè)數(shù)組?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!