S
S
SmirnovaNastya2021-11-18 19:01:25
PHP
SmirnovaNastya, 2021-11-18 19:01:25

How to compare arrays in PHP and add non-existent properties after comparison?

How to add to the array $array2 from the array $array those properties that are not in $array2? Comparison by name only. The new element in the $array2 array from the $array array does not need to be passed the id property, only the name. You cannot copy it completely, since id is unique.

$array = [
0 => [
'name'=> 'Any',
'id' => 14
],
1 => [
'name'=> 'Oleg',
'id' => 12
],
2 => [
'name'=> 'Maks',
'id' => 16
],
];


$array2 = [
0 => [
'name'=> 'Any',
'name'=> 'Oleg',
'id' => 13
],
];

i.e. the output should look like this:
$array2 = [
0 => [
'name'=> 'Any',
'id' => 11
],
1 => [
'name'=> 'Oleg',
'id' => 13
],
2 => [
'name'=> 'Maks'
],
];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lil_koi, 2021-11-18
@SmirnovaNastya

use a foreach loop inside foreach, look for the first element in the second array, if not found, then push to the second array

G
grek_cheburek, 2021-11-18
@grek_cheburek

I would also loop through the first array, compare it with the second, and if the second does not have a name, as in the first, then I add it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question