在PHP中的两个关联数组上进行完全外部联接 [英] Full Outer Join on two associative arrays in PHP
问题描述
我有两个php数组,如下所示。现在,我想对这两个数组进行完全外部联接(如SQL中的联接)。 Id可以视为唯一键。最简单的方法是什么?
I have two php arrays as shown below. Now I would like get a full outer join (like in SQL) on these two arrays. "Id" can be considered as unique key. What is the easiet way to achieve this?
数组1(旧数据):
array(
[0]=>array("Id"=>101, "Name"=>"Bob",....),
[1]=>array("Id"=>102, "Name"=>"Scott",....),
[2]=>array("Id"=>103, "Name"=>"Philips",....),
[3]=>array("Id"=>104, "Name"=>"Marker",....)
)
数组2(新数据):
array(
[0]=>array("Id"=>102, "Name"=>"Scott",....),
[1]=>array("Id"=>103, "Name"=>"Philips",....),
[2]=>array("Id"=>104, "Name"=>"Mark",....),
[3]=>array("Id"=>105, "Name"=>"Nix",....)
)
结果数组:
`array(
[0]=>array("Status"=>"d", "Id"=>101, "Name"=>"Bob",....),
[1]=>array("Status"=>"s", "Id"=>102, "Name"=>"Scott",....),
[2]=>array("Status"=>"s", "Id"=>103, "Name"=>"Philips",....),
[3]=>array("Status"=>"c", "Id"=>104, "Name"=>"Mark",....),
[4]=>array("Status"=>"n", "Id"=>105, "Name"=>"Nix",....)
)`
状态->
` d-删除
s-相同,记录无变化值
"s" - Same, no change in record values
c-更改任何记录值
n-新建记录`
推荐答案
您可以通过将两个数组的 Id字段作为键来重新索引两个数组
you may reindex both arrays by putting their "Id" fields as keys
array(
[101]=>array("Id"=>101, "Name"=>"Bob",....),
[102]=>array("Id"=>102, "Name"=>"Scott",....),
[103]=>array("Id"=>103, "Name"=>"Philips",....),
[104]=>array("Id"=>104, "Name"=>"Marker",....)
)
然后为每个循环第二个首先进入状态,可以通过一些数组比较轻松地确定状态状态为 s和 c的部分,array_key_exists为 d。
array_diff(数组2,数组1)的结果应检索状态为'n'的条目。
then cycling the second for each entry in the first, status can be easly decided with some array comparison function for statuses 's' and 'c', array_key_exists for 'd'. The result of array_diff (array 2, array 1) should retrieve entries with status 'n'
so:
$result = Array();
foreach(array1 as $k1 => $v1){
if(!array_key_exists($k1, $array2)){
$status = 'd';
}else{
if(are_the_same($v1, $array2[$k1])) $status = 's';
else $status = 'c';
}
$result[]=array("Status"=>$status, "Id"=>$k1, "Name"=>$v1['Name'],....)
}
然后您可以使用数组合并y array_diff的组合以填充 d状态。
我想您可以为此编写自己的代码;-)
then you may use a combination of array merge y array_diff to fill in the 'd' status ones. I think you can write your own code for this ;-)
这篇关于在PHP中的两个关联数组上进行完全外部联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!