我想要联盟2阵列$A
和$B
示例:
$A = Array(
0=>array(
'lable' =>"label0",
'id_poste'=>1,
'id_part'=>11
),
1=>array(
'lable' =>"label1",
'id_poste'=>2,
'id_part'=>12
),
2=>array(
'lable' =>"label2",
'id_poste'=>3,
'id_part'=>13
),
3=>array(
'lable' =>"label3",
'id_poste'=>4,
'id_part'=>14
)
);
$B = Array(
0=>array(
'lable' =>"label0",
'id_poste'=>1,
'id_part'=>11
),
1=>array(
'lable' =>"label1_X",
'id_poste'=>2,
'id_part'=>12
),
2=>array(
'lable' =>"label2",
'id_poste'=>3,
'id_part'=>13
),
3=>array(
'lable' =>"label3_X",
'id_poste'=>4,
'id_part'=>14
)
);
这两个数组之间的并集结果将是
/*
$result => Array(
0=>array(
'lable' =>"label0",
'id_poste'=>1,
'id_part'=>11
),
1=>array(
'lable' =>"label1",
'id_poste'=>2,
'id_part'=>12
),
2=>array(
'lable' =>"label1_X",
'id_poste'=>2,
'id_part'=>12
)
3=>array(
'lable' =>"label2",
'id_poste'=>3,
'id_part'=>13
),
4=>array(
'lable' =>"label3",
'id_poste'=>4,
'id_part'=>14
),
5=>array(
'lable' =>"label3_X",
'id_poste'=>4,
'id_part'=>14
)
);
*/
我尝试过:
$C = $A+$B;
echo '<pre>';
print_r($C);
echo '</pre>'
但结果不是我的预期?有人可以帮忙吗?
由于
EIDT:
如果使用array_merge($A, $B);
Array
(
[0] => Array
(
[lable] => label0
[id_poste] => 1
[id_part] => 11
)
[1] => Array
(
[lable] => label1
[id_poste] => 2
[id_part] => 12
)
[2] => Array
(
[lable] => label2
[id_poste] => 3
[id_part] => 13
)
[3] => Array
(
[lable] => label3
[id_poste] => 4
[id_part] => 14
)
[4] => Array
(
[lable] => label0
[id_poste] => 1
[id_part] => 11
)
[5] => Array
(
[lable] => label1_X
[id_poste] => 2
[id_part] => 12
)
[6] => Array
(
[lable] => label2
[id_poste] => 3
[id_part] => 13
)
[7] => Array
(
[lable] => label3_X
[id_poste] => 4
[id_part] => 14
)
)
就像我们在这里看到的那样,数组是重复的:所以我们使用array_unique
但是我们仍然遇到错误或警告。
Array to string conversion in C:\Program Files\EasyPHP-12.1\www\PHP\array_union.php on line 86
答案 0 :(得分:3)
我得到的解决方案有点棘手。 我将合并A及其与B的区别。为了确定这种差异,我使用array_udiff: 我认为它很棘手,因为它依赖于标签密钥的识别。
$C = array_merge($A,
array_udiff($B, $A,
function($a,$b){
return strcmp($a['lable'],$b['lable']);
}
)
);
答案 1 :(得分:0)
array_merge($A, $B);
是您正在寻找的
答案 2 :(得分:0)
为此目的使用array_merge()
$C = array_merge($A,$B);
echo '<pre>';
print_r($C);
echo '</pre>'
答案 3 :(得分:0)
您可以使用array_merge()
。因为您需要删除重复项,所以您还必须使用array_unique()
....
$C = array_unique(array_merge($A,$B), SORT_REGULAR);
echo '<pre>';
print_r($C);
echo '</pre>'
它给了我正确的结果
Array
(
[0] => Array
(
[lable] => label0
[id_poste] => 1
[id_part] => 11
)
[1] => Array
(
[lable] => label1
[id_poste] => 2
[id_part] => 12
)
[2] => Array
(
[lable] => label2
[id_poste] => 3
[id_part] => 13
)
[3] => Array
(
[lable] => label3
[id_poste] => 4
[id_part] => 14
)
[5] => Array
(
[lable] => label1_X
[id_poste] => 2
[id_part] => 12
)
[7] => Array
(
[lable] => label3_X
[id_poste] => 4
[id_part] => 14
)
)
答案 4 :(得分:0)
<?php
$input = array_merge( $A, $B );
$input = array_map( "unserialize", array_unique(array_map("serialize", $input)) );
var_dump( $input );