1

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
3
  • so, you want to remove values from array exist in database, RIGHT? Commented Oct 31, 2015 at 12:05
  • Remove the value from $gameIds if the id already exists in database Commented Oct 31, 2015 at 12:09
  • you can loop through $maches and do unset if found in $gameIds. Commented Oct 31, 2015 at 12:13

1 Answer 1

0

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.
Sign up to request clarification or add additional context in comments.

3 Comments

I will take a check on this first thing tomorrow, also is endif; and endforeach; a better approach than just }? Is there a resource I can read about that
It just the same, I was to really influenced coding style based on my team. Oh, you can refer array_diff here: php.net/manual/en/function.array-diff.php
i fixed it adding another loop into my script thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.