php - 将 php 数组与 sql 结果进行比较并执行某些操作

标签 php mysql arrays

我有一个来自 JSON 文件的数组和来自数据库的几行。使用array-search我可以检查 $all_results 数组中的值是否存储在我的数据库ma​​tch_id 列中。

如果找到值,我将成功使用 $show_key 变量获取 key 。现在,我想在找到 key 时执行此操作,如果没有找到 key 则执行该操作,但我不知道如何执行此操作!

我尝试了is_int,它不起作用并以大于0解决方案结束,如果没有找到一个值,它正是我想要的键为 0

帮助会很棒。 非常感谢!

$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
            }

        }

最佳答案

PHP: array_search

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

更换您的条件-

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

有了这个-

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

如果已找到 key ,则返回 key ;如果未找到,则返回 false。

另外,这一行是错误的-

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

用这个替换它以查看 key -

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

关于php - 将 php 数组与 sql 结果进行比较并执行某些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41894045/

相关文章:

php - Symfony 使 :entity annotation mapping error

php - Facebook PHP-SDK getUser() 始终返回 0

mysql - SQL 删除与级联

python - 将最大 numpy 数组偏移量转换为元组?

php - MySQL Laravel 5.4 导入数据库问题

php - 使用 Objective-C 从服务器获取数据

php - 来自不同来源的两次Ajax调用导致一个静默失败

php - ajax 成功函数未触发

java - 从数据文件中的一行整数中查找最大值和最小值

arrays - 如何在 Swift 中对元组数组中的相似元组进行平均