gpt4 book ai didi

php/mysql 随机排序日期

转载 作者:行者123 更新时间:2023-11-29 08:49:22 25 4
gpt4 key购买 nike

我在寻找一种在两个固定时间戳之间生成随机日期的方法时发现了这个很棒的功能:

 function randomDate($start_date, $end_date)
{
// Convert to timestamps
$min = strtotime($start_date);
$max = strtotime($end_date);

// Generate random number using above bounds
$val = rand($min, $max);

// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}

Source and credit

但我正在寻找一种按顺序(开始日期到结束日期)生成日期的方法,因为我已经使用它来生成要插入数据库的日期。

问题是我的帖子是 ORDER BY id DESC 并使用“按原样”功能,因为它们是随机的,日期最终不同步。

即:

post id 4 - date = 2010-07-11 14:14:10
post id 3 - date = 2012-02-22 18:23:21
post id 2 - date = 2011-03-17 13:52:47
post id 1 - date = 2011-08-14 15:33:50

我需要它们与帖子 ID 同步。

现在您在想为什么不将查询更改为 ORDER BY date DESC 呢? ...好吧,这会弄乱我已经编写的 99% 的代码,因为还有其他列/行依赖于它 ORDER BY id DESC ,因此在插入数据库时​​对日期进行排序是唯一的解决方案。

更新:

这是我尝试使用 madfriend 代码进行的操作,但所有日期都相同,我哪里出错了?

function randomDate($startdate, $enddate){
$min = strtotime($startdate);
$max = strtotime($enddate);
$val = rand($min, $max);
return date('Y-m-d H:i:s', $val);
}

$query = "SELECT * FROM foo";
$num = mysql_num_rows(mysql_query($query));

$randate = randomDate('2010-07-12 09:13:40', '2012-06-12 09:13:40');

$dates = array($randate);
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates);
while($date = array_shift($dates)) {

$update = "UPDATE foo SET date='{$date}'";
mysql_query($update);

}

加上得到注意: undefined variable :startdate

最佳答案

我不太确定您是在谈论创建还是修改现有行。

更新:这里的基本思想非常简单。首先,使用 SELECT COUNT(*) FROM your_posts_table 查询计算帖子数量。之后:

// $num is number of posts
$dates = array();
for ($i = 0; $i < $num; $i++) {
$dates[] = randomDate($startdate, $enddate);
}
sort($dates); // Sort dates in ascending order
while($date = array_shift($dates)) {
// now $date won't be lower than it was in previous iterations.
// use it to update your table
}

插入:如果您正在谈论插入并希望使最新的发布日期随机但最大,那么您可以执行以下操作:

  • 首先,选择上次添加的发布日期。
  • 其次,调用 randomDate,并将 $startdate 设置为上次添加帖子的日期。
  • 最后,插入包含此日期的新行。

关于php/mysql 随机排序日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11702398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com