Dragonsnap
Dragonsnap

Reputation: 953

Compare two multidimensional objects with an array inside them

So say I have two arrays:

$a: 
array(3) => {
    [0] => 
    object(stdClass)#1 (2){
        ["id"] => int(34999)
        ["name"] => string(4) "John"
    }
    [1] => 
    object(stdClass)#2 (2){
        ["id"] => int(48291)
        ["name"] => string(4) "John"
    }
    [2] => 
    object(stdClass)#3 (2){
        ["id"] => int(23124)
        ["name"] => string(4) "Sam"
    }
}

and

$b: 
array(2) => {
    [0] => 
    object(stdClass)#1 (2){
        ["id"] => int(34999)
        ["name"] => string(4) "John"
    }
    [2] => 
    object(stdClass)#3 (2){
        ["id"] => int(23124)
        ["name"] => string(4) "Sam"
    }
}

with the assumption being $b is ALWAYS a subset of $a, how do I get the difference between $a and $b, based on id? I tried doing two foreach loops within each other, but since I'm doing this with an array with ~34k elements, it's taking forever. A result would be something like:

$a_diff_b:
array(1) => {
    [0] => 
    object(stdClass)#1 (2){
        ["id"] => int(48291)
        ["name"] => string(4) "John"
    }
}

Upvotes: 0

Views: 68

Answers (1)

user1597430
user1597430

Reputation: 1146

Method one:

$ids_a = array_column($a, 'id');
$ids_b = array_column($b, 'id');

$ids_diff = array_diff($ids_a, $ids_b);
$ids_diff = array_flip($ids_diff);

$result = [];

foreach ($a as $item)
{
    if (isset($ids_diff[$item->id]))
    {
        $result[] = $item;
    }
}

Method two:

$ids = [];

foreach ($b as $item)
{
    $ids[$item->id] = true;
}


$result = [];

foreach ($a as $item)
{
    if (!isset($ids[$item->id]))
    {
        $result[] = $item;
    }
}

Upvotes: 1

Related Questions