简体   繁体   中英

How to merge these two arrays?

I want to merge those two arrays and get only the unique key values. Is there a php function for this? array_merge() doesn't work.

Array
(
    [1] => 3
    [2] => 4
    [3] => 1


)

Array
(
    [1] => 3
    [2] => 1
    [3] => 2

)

RESULT ARRAY THAT I WANT

Array
(
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4

)
$values = array_unique(array_merge($array1, $array2));
sort($values);

This returns the unique values from array1 and array2 (as per your example).

Try it here: http://codepad.org/CeZewRNT

See array_merge() and array_unique() .

$merged = array_unique(array_merge($array1, $array2));

Following peice of code gives exact what you wants but the question is do you really want the keys in the result are starting from 1 instead of 0? If you don't Arnaud his option is the best solution.

$array1 = array(
    1 => 3,
    2 => 4,
    3 => 1
);

$array2 =  array(
    1 => 3,
    2 => 1,
    3 => 2
);

$values = array_unique(array_merge($array1, $array2));
$keys = array_keys(array_fill_keys($values, ''));
$result = array_combine($keys, $values);
asort($result);

var_dump($result);

尝试这个:

$merged = array_unique(array_merge($array1, $array2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM