我有一个来自 JSON 文件的数组和来自数据库的几行。使用array-search我可以检查 $all_results 数组中的值是否存储在我的数据库match_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
}
}
最佳答案
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/