0

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
            }

        }
1
  • why don't you print a few key['id'] and the results from the db and compare it yourself and see that where there ids matching or not. Commented Jan 27, 2017 at 12:37

1 Answer 1

2

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

2 Comments

@RiggsFolly thanks! though I was going to edit it anyhow.
Thank you very much! Helped. Works.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.