user4815703
user4815703

Reputation:

Remove from array if id exists in database?

I am pulling data from an api and as such i have a loop that stores some ids into an array.

What i need to do is select all ids from my database and then remove any ids that have been found in the database from the initial array. so i can continue to query the api for ids that i do not have currently.

To make more sense please look below:

$matches = $database->get_results('SELECT match_id FROM `matches` WHERE `order_id`='.$order_id);

if ($matchlist->totalGames !== 0) {
    foreach ($matchlist as $key) {
      $gameIds[] = $key->matchId;
    }
}

I need to remove the ids from $gameIds if they already are stored in the $matches.

Any ideas? Thanks

I have tried:

$matches = $database->get_results('SELECT `match_id` FROM `matches` WHERE `order_id`='.$order_id);
if ($matchlist->totalGames !== 0) {
    foreach ($matchlist as $key) {
      $gameIds[] = $key->matchId;
    }
    $arr_matches = object2array($matches);
    $new_array = array_diff($arr_matches, $gameIds);
    var_dump($new_array);
}

error:

Catchable fatal error: Object of class stdClass could not be converted to string

Upvotes: 1

Views: 748

Answers (1)

Nere
Nere

Reputation: 4097

Step 1: Change object to array

function object2array($object) 
{
    if (is_object($object)):
        foreach ($object as $key => $value):
            $array[$key] = $value;
        endforeach;
    else:
        $array = $object;
    endif;
    return $array;
}

Step 2:

$arr_matches = object2array($matches)

$new_array = array_diff($arr_matches , $gameIds);
// Will remove all elements contained in $gameIds from $arr_matches array.

Upvotes: 0

Related Questions