php - 通过将记录存储到数组中获取表中缺失的 ID,并使用 for 循环比较该组数字

标签 php mysql

我目前正在开发一个程序,该程序获取表中丢失的 ID,我想到的是将 ID 存储到数组中并使用 for 循环来检查数组中是否存在数字如果存在,则将其归类为丢失 ID。我还使用了 php 函数 - in_array() 来检查数组中是否存在数字。

这是我想出的代码,但我最终只显示 for 循环中的数字。

<?php
	include 'dbconnect.inc'; //just to the the dbconnect for connecting into the database.

	$numbers = array(1, 2, 4, 6, 7, 9);
	$arrlength = count($numbers);

		$query = "SELECT id FROM existing";
		$result = mysqli_query($conn, $query);
		$existing = array();

		while ($row = mysqli_fetch_assoc($result)) {
			$existing[] = $row;
		}
		
		for ($i=0; $i<7358; $i++) {
			if (in_array($i, $existing)) {
				echo $i . " is a missing ID <br>";
			} elseif(!in_array($i, $existing)) {
				echo $i . " exists in the table <br>";
			}
			
		}

?>

与在 SQL 中使用临时表相比,我更喜欢此解决方案,因为它需要的不仅仅是加载查询,而且对于网页来说并不好。

希望你能帮助我。谢谢!

最佳答案

来自this answer :

要获取缺失的范围:

SELECT a.id+1 AS 'Missing From', MIN(b.id)-1 AS 'Through'
FROM existing AS a
JOIN existing AS b ON a.id < b.id
GROUP BY a.id
HAVING a.id+1 < MIN(b.id)

fiddle

关于php - 通过将记录存储到数组中获取表中缺失的 ID,并使用 for 循环比较该组数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348963/

相关文章:

php - 按字母范围对数组元素进行分组

php - 两个相同模型/表之间的两种关系

php - 当页面加载 php 错误时,与服务器的连接被重置

php - Mysql中的空格删除

php - 如何从 mysql 解析 JSON 图像并填充 ListView

php - 从管理面板创建属性

mysql - MySql : number of rows or size of file? 性能瓶颈

php - 如何使用 PHP 从 MySQL 创建嵌套菜单?

php - Symfony onFlush 学说监听器

php - 使用 [php] 代码从一个特定的 [mysql] 数据库表中提取数据列表,但只有第一个 <option></option> 实际上是提取数据