我有一个大主机名数组及其对应的位置。
Array ( [ABC01] => Array ( [hostid] => 12345
[lat] => 123
[lon] => 123
[adr] => 126 Foo Street
[city] => Rocky Hill
[state] => Connecticut
[country] => USA )
[ABC02] => Array ( [hostid] => 12346
[lat] => 345
[lon] => 345
[adr] => 123 Foo Street
[city] => Boston
[state] => Massachusetts
[country] => USA )
[ABC03] => Array ( [hostid] => 12346
[lat] => 345
[lon] => 345
[adr] => 123 Foo Street
[city] => New York City
[state] => New York
[country] => USA )
.....)
我将它与一个较小的数组进行比较 - 相同的主机名,但它链接到IP地址:
Array ( [ABC01] => Array ( [ip] => 192.168.2.1 )
[ABC02] => Array ( [ip] => 192.168.2.2 )
[ABC03] => Array ( [ip] => 192.168.2.3 )
)
我想创建以下数组:
[ABC02] => Array ( [hostid] => 12346
[lat] => 345
[lon] => 345
[adr] => 123 Foo Street
[city] => Boston
[state] => Massachusetts
[country] => USA
[ip] => 192.168.2.1)
我试图找到数组的交集,然后将两者合并(找到相同的键,然后合并)。我尝试了各种功能,但最终的结果绝不是我想要的。
我设法找到一个函数here来合并公共密钥,但它在包含另一个数组中的位置字段的数组中的数组中返回IP,如下所示:
Array ( [ABC02] => Array ( [0] => Array ( [hostid] => 12346
[lat] => 345
[lon] => 345
[adr] => 123 Foo Street
[city] => Boston
[state] => Massachusetts
[country] => USA
[1] => Array ( [ip] => 192.168.2.1) ) )
有更简单的方法吗?
答案 0 :(得分:4)
内置PHP函数非常简单:
$result = array_merge_recursive($large, $small);
根据您的评论,只获取常见的值,然后合并。这假定$small
中的所有键都在$large
:
$result = array_merge_recursive(array_intersect_key($large, $small), $small);
不做出假设,如果其中任何一个中的密钥不在另一个中,那么:
$result = array_merge_recursive(array_intersect_key($large, $small),
array_intersect_key($small, $large));