运行 mysql 查询后,我得到包含以下形式的数据的列表:
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["event_id"]. " - timestamp: ". $row["event_start"]. " " . $row["event_duration"] . "<br>";
}
}
基本上每一行都有三个字段:
event_id | event_start | event_duration
现在,我想要实现的是在 php 中迭代返回的行,并找到一个可以放置带有 event_start 时间戳和 event_duration 的新事件的位置。我正在寻找的地方必须是空闲的,并且准备好在整个 event_duration 期间填充 event_id。
简单示例:假设数据库中有 4 个事件:
e1 starts at 1:00:10 and lasts 30 seconds
e2 starts at 1:00:40 and lasts 20 seconds
e3 starts at 1:01:30 and lasts 40 seconds
e4 starts at 1:02:50 and lasts 20 seconds.
现在我想插入持续 20 秒的 e5,所以完美的位置应该在 e2 和 e3 之间,所以在我提供 e5 的 id 及其持续时间后,我想收到我可以放在哪里的时间戳(在我的示例中为 1:01:00)。如何在 php 中创建这样的循环?
编辑:
为我返回数据的选择查询如下:
select event_id, event_start, event_duration
from table
where event_start>= 'begin-boundary-time'
and event_start+ event_duration <= 'end-boundary-time'
最佳答案
如果您真正使用 MySQL 数据库来存储事件,我不会担心循环数据并找到插入位置。当您在 SQL 查询中使用 order 语句查看事件时,可以对信息进行排序。这很可能(取决于表的大小、碎片或索引)比每次运行 PHP 循环更快。您的插入将更加准确,因为它们不会被延迟循环查找插槽。
关于php - 循环遍历 php 中的表格以找到适合我的数据的最佳位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29518977/