P
P
Pavel2021-06-22 11:18:23
PHP
Pavel, 2021-06-22 11:18:23

How to get elements of one array that are missing in another?

I'm trying to compare 2 arrays whose keys are named differently, but I need to compare their values.
The problem is that in the first array these values ​​are repeated many times.

First array:

$arr= [ [ "user_id" => "100", 
               "Цена" => 100,
               "Количество" => 15 
             ],
             [ "user_id" => "100", 
               "Цена" => 60,
               "Количество" => 25,
             ],
             [ "user_id" => "100", 
               "Цена" => 180,
               "Количество" => 7 
             ]
           ];

Second:

$arr2= [ [ "users_id" => "100", 
               "Цена" => 100,
               "Количество" => 15 
             ],
             [ "users_id" => "101", 
               "Цена" => 60,
               "Количество" => 25,
             ],
             [ "users_id" => "102", 
               "Цена" => 180,
               "Количество" => 7 
             ]
           ];

In arr1 user_id, and in arr2 users_id, and I want to find the difference and take only the data from the second array to get this result:

$result = [
 [ "users_id" => "101", 
               "Цена" => 60,
               "Количество" => 25,
             ],
             [ "users_id" => "102", 
               "Цена" => 180,
               "Количество" => 7 
             ]
];

I'm trying to write via function + 2 foreach loops:

function array_diff_unic($array1, $array2) {
        $result=[];
        foreach($array1 as $key => $value) {
            foreach($array2 as $key2 => $value2) {
                if( $array1['user_id'] != $array2['users_id'] ) {
                    $result[$key] = $value2;
                }
            }
        }
        return $result;
    }

But it does not work, besides, it is not clear how to remove duplicates.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-22
@mrusklon

$ids = array_unique(array_column($arr, 'user_id'));
$result = array_filter($arr2, fn($n) => !in_array($n['users_id'], $ids));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question