Robin Alexander
Robin Alexander

Reputation: 1004

Compare php array with sql results and do something

I have an array coming from a JSON file and a few rows from my database. Using array-search I can check if values from my $all_results array are stored in my databases match_id column.

If values are found I get the key with my $show_key variable successfully. Now, I'd like to do this when keys are found and do that if none are found, but I have no idea how to do this!

I tried is_int, which does not work and ended in the larger than 0 solution, which does exactly what I want if there wouldn't be a found value whose key is 0.

Help would be awesome. Thank you very much!

$json=file_get_contents('file.json');
$decode = json_decode($json,true);
$results = $decode['data'];

    foreach ($results as $key )
    {
        $all_results[]= $key['id'];
    }

        $pdo = new PDO('xxx');
        $sql = "SELECT * FROM results";

        foreach ($pdo->query($sql) as $row) 

        {

            echo $show_key = array_search($row['match_id'], $all_matches).'<br/>';

            if (array_search($row['match_id'], $all_results) > 0 )
            {
                // do this
            }
            else
            {
                // do that
            }

        }

Upvotes: 0

Views: 742

Answers (1)

xRahul
xRahul

Reputation: 364

PHP: array_search

Returns the key for needle if it is found in the array, FALSE otherwise.

Replace your condition-

if (array_search($row['match_id'], $all_results) > 0 )

with this-

if (array_search($row['match_id'], $all_results) !== FALSE )

This will return the key if the key has been found and false if it hasn't.

Also, this line is wrong-

echo $show_key = array_search($row['match_id'], $all_matches).'<br/>';

Replace it with this to see the keys-

echo $show_key = array_search($row['match_id'], $all_results).'<br/>';

Upvotes: 2

Related Questions