Super Mario's Yoshi Super Mario's Yoshi -4 years ago 64
PHP Question

Compare two arrays and populate with elements that don't exist in first array

I have two arrays that looks like this, i simply need to take object with id 3 from $allItems and put it in $existingItems array, i tried something like this but im unable just to take elements that don't exist in $existingItems.

$existingItems = array[{
id: 1
name: 'jon doe',
events: [{..},{..}]
},{
id: 2,
name: 'jane doe',
events: [{..},{..}]
}]

$allItems = array[{
id: 1
name: 'jon doe'
events: null
},{
id: 2,
name: 'jane doe',
events: null
},{
id: 3,
name: 'David Beckam',
events: null
}];

foreach ($existingItems as $key => $existingValue) {
$found = false;
foreach ($allItems as $key => $value) {
if($existingValue['id'] === $value['id']) {
$found = true;
break;
}
if($found == false)
$existingItems [] = $value;
}
}

Answer Source

You have your foreach loops in the wrong order. Since you are looping the existing array in the outer loop, and the existing array doesn't have any id=3, it won't be able to find it. You need to put $allItems as the outer loop and $existingItems as the inner loop like this:

foreach ($allItems as $value) {
    $found = false;
    foreach ($existingItems as $key => $existingValue) {
        if($existingValue['id'] === $value['id']) {
            $found = true;
            break;
        }
    }
    if($found == false) {
        $existingItems[] = $value;
    }
}

Also note that the $found == false check had to be moved outside the inner loop because you have to wait until you search every item in the inner loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download