2017-07-05 18 views
5

mam te trzy tablice:Jak utworzyć tablicę złożoną, która zawiera maksymalną długość?

$arr1 = ['one', 'two', 'three']; 
$arr2 = ['three', 'four']; 
$arr3 = ['two', 'five', 'six', 'seven']; 

i to oczekiwany rezultat:

/* Array 
    (
     [0] => one 
     [1] => two 
     [3] => three 
     [4] => four 
     [5] => five 
     [6] => six 
     [7] => seven 
    ) 

Here jest moje rozwiązanie, które nie działa zgodnie z oczekiwaniami:

print_r(array_unique($arr1 + $arr2 + $arr3)); 
/* Array 
    (
     [0] => one 
     [1] => two 
     [2] => three 
     [3] => seven 
    ) 

Jak mogę to zrobić?

Odpowiedz

9

Użyj tego:

array_unique(array_merge($arr1,$arr2,$arr3), SORT_REGULAR); 

będzie scalić tablic do jednego, a następnie usuwa wszystkie duplikaty

Testowany Here

To Wyjścia:

Array 
(
    [0] => one 
    [1] => two 
    [2] => three 
    [4] => four 
    [6] => five 
    [7] => six 
    [8] => seven 
) 
3

myślę, że to wola działa dobrze

$arr1 = ['one', 'two', 'three']; 
$arr2 = ['three', 'four']; 
$arr3 = ['two', 'five', 'six', 'seven']; 
$n_array = array_values(array_unique(array_merge($arr1 , $arr2 , $arr3))); 
echo "<pre>";print_r($n_array);echo "</pre>";die; 

Wyjście jest

Array 
(
    [0] => one 
    [1] => two 
    [2] => three 
    [3] => four 
    [4] => five 
    [5] => six 
    [6] => seven 
) 
+0

Najpiękniejszych odpowiedź, można również dbał o klucze, jak również. –

+0

Dzięki @ShaunakShukla –

0

użycie array_merge wtedy, array_unique

$arr1 = ['one', 'two', 'three']; 
$arr2 = ['three', 'four']; 
$arr3 = ['two', 'five', 'six', 'seven']; 

print_r(array_unique (array_merge($arr1,$arr2,$arr3))); 

Wynik

Array ([0] => one [1] => two [2] => three [4] => four [6] => five [7] => six [8] => seven) 
1

Just Do tego .. używać array_uniqe

Demo: https://eval.in/827705

<?php 

    $arr1 = ['one', 'two', 'three']; 
    $arr2 = ['three', 'four']; 
    $arr3 = ['two', 'five', 'six', 'seven']; 


    print_r ($difference = array_unique(array_merge($arr1, $arr2,$arr3))); 
    ?> 
0
<?php 
    $arr1 = ['one', 'two', 'three']; 
    $arr2 = ['three', 'four']; 
    $arr3 = ['two', 'five', 'six', 'seven']; 
    $merge_arr = array_merge($arr1,$arr2,$arr3); 
    $unique_arr = array_unique($merge_arr); 
    echo '<pre>'; 
     print_r($unique_arr); 
    echo '</pre>'; 
?> 

Wyjście

Array 
(
    [0] => one 
    [1] => two 
    [2] => three 
    [4] => four 
    [6] => five 
    [7] => six 
    [8] => seven 
) 
Powiązane problemy