繁体   English   中英

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

[英]Compare php array with sql results and do something

我有一个来自JSON文件的数组,并且数据库中有几行。 使用array-search我可以检查$ all_results数组中的值是否存储在数据库的match_id column中

如果找到值,则成功使用$ show_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

如果在数组中找到该针,则返回该针的键,否则返回FALSE。

替换您的条件-

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

有了这个-

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

如果找到了密钥,它将返回密钥;如果没有,则返回false。

另外,这行是错误的-

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

替换它以查看键-

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM