There are two multi-dimensional arrays:

$array1 = array( 0 => array("cancelled" => "0", "id"=>"65"), 1 => array("cancelled" => "1", "id"=>"33")); $array2 = array( 0 => array("cancelled" => "0", "id"=>"11"), 1 => array("cancelled" => "0", "id"=>"27"), 2 => array("cancelled" => "0", "id"=>"65")); 

How to elegantly merge them so that an array with elements from the first array and the second one comes out, but all the values ​​were unique, not repeated?

If you use $ array3 = array_merge ($ array1, $ array2); it will turn out:

 $array3 = array( 0 => array("cancelled" => "0", "id"=>"65"), 1 => array("cancelled" => "1", "id"=>"33") 2 => array("cancelled" => "0", "id"=>"11"), 3 => array("cancelled" => "0", "id"=>"27"), 4 => array("cancelled" => "0", "id"=>"65")); 

Need

 $array3 = array( 0 => array("cancelled" => "0", "id"=>"65"), 1 => array("cancelled" => "1", "id"=>"33") 2 => array("cancelled" => "0", "id"=>"11"), 3 => array("cancelled" => "0", "id"=>"27")); 

P.S. The uniqueness of the value can be determined also by the field of the array of the value of 'id' - in my case, if id is the same then the values ​​are the same

  • Well duck filter the resulting result throwing repeated? - teran

2 answers 2

In case it doesn’t matter when the duplicate check will be performed, then duplicate values ​​can be filtered after the merging of arrays. For example, you can do this as follows.

Initial data:

 $array1 = [ ["cancelled" => "0", "id"=>"65"], ["cancelled" => "1", "id"=>"33"] ]; $array2 = [ ["cancelled" => "0", "id"=>"11"], ["cancelled" => "0", "id"=>"27"], ["cancelled" => "0", "id"=>"65"] ]; 

Merging and eliminating repetitions using an additional associative (by id ) array.

 $array3 = array_merge($array1, $array2); $result = []; foreach($array3 as $v){ if(isset($result[$v['id']])) continue; // повтор элемента $result[$v['id']] = $v; } $result = array_values($result); //Если нужны ключи от 0 до N. 

    This is how I did, but there is a double loop and a check before merging:

     $array1 = array( 0 => array("cancelled" => "0", "id"=>"65"), 1 => array("cancelled" => "1", "id"=>"33")); $array2 = array( 0 => array("cancelled" => "0", "id"=>"11"), 1 => array("cancelled" => "0", "id"=>"27"), 2 => array("cancelled" => "0", "id"=>"65")); foreach($array1 as $key1=>$value1){ //Собираем ID по первому массиву foreach($array2 as $key2=>$value2){ //Собираем ID по второму массиву if($value2["id"]==$value1["id"]) {//Есть ли одинаковые unset($array2[$key2]);//Удаляем если есть одинаковые } } } print_r(array_merge($array1, $array2));//Сливаем и выводим