I Want to Union 2 array $A
and $B
Example:
$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
)
);
The result of union between these two array will be
/*
$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
)
);
*/
I have tried with :
$C = $A+$B;
echo '<pre>';
print_r($C);
echo '</pre>'
But the result is not what I expected ? Anybody could help please?
Thanks
EIDT:
if using 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
)
)
Like we see here the array is duplicated : So we using array_unique
But we still got an error or warning .
Array to string conversion in C:\Program Files\EasyPHP-12.1\www\PHP\array_union.php on line 86
I get a solution that is kind a tricky. I will merge A and its difference with B. To determine this difference, I use array_udiff: I think it's tricky because it relies on the identification with lable key.
$C = array_merge($A,
array_udiff($B, $A,
function($a,$b){
return strcmp($a['lable'],$b['lable']);
}
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With