如何比较 php 中一个变量中存储的多个日期?
How to compare multiple dates stored inside one variable in php?
我正在使用 ACF 创建自定义 wordpress 字段。使用 repeater
字段,我可以使用相同的字段添加多个内容。目前我确实在中继器字段 dates_list
:
中存储了两个变量
si-date
– 日期(格式 20160225)
si-special
– 随机文本
我可以将转发器的所有行存储在一个 var 中,select dates_list
:
的某一行
<?php
$rows = get_field('dates_list' ); // get all the rows
$first_row = $rows[0]; // get the first row
$first_row_image = $first_row['si-date' ]; // get the sub field value
?>
如何使用此方法比较 si-date
和 select 包含下一个日期的行中的所有日期?
您将必须遍历所有行并检查它 "manually"。我没有测试过这段代码,但我认为这可能是一个好的开始:
<?php
$rows = get_field('dates_list');
$actual_date = date('Ymd');
$selected_date = '99999999';
$selected_row = null;
foreach ($rows as $row) {
if ($row['si-date'] > $actual_date AND $row['si-date'] < $selected_date) {
$selected_date = $row['si-date'];
$selected_row = $row;
}
}
if (is_array($selected_row)) {
// do your stuff your with the row
}
?>
如果您只需要获取今天之后的下一个日期,您可以参考这里解释得很好的 usort 函数,将最近的日期排在最前面:Sorting an array with DateTime strings?
以这种方式对数组进行排序后,您就可以处理该数组以找到比今天大的第一个日期。也许是这样的:
foreach($sorted_dates_array as $row){
//If the date is greater than the current time then return the row
if(strtotime($row['si-date'])>time())
{
return $row;
}
//There are no dates that are yet to be completed
return false;
}
我正在使用 ACF 创建自定义 wordpress 字段。使用 repeater
字段,我可以使用相同的字段添加多个内容。目前我确实在中继器字段 dates_list
:
si-date
– 日期(格式 20160225)si-special
– 随机文本
我可以将转发器的所有行存储在一个 var 中,select dates_list
:
<?php
$rows = get_field('dates_list' ); // get all the rows
$first_row = $rows[0]; // get the first row
$first_row_image = $first_row['si-date' ]; // get the sub field value
?>
如何使用此方法比较 si-date
和 select 包含下一个日期的行中的所有日期?
您将必须遍历所有行并检查它 "manually"。我没有测试过这段代码,但我认为这可能是一个好的开始:
<?php
$rows = get_field('dates_list');
$actual_date = date('Ymd');
$selected_date = '99999999';
$selected_row = null;
foreach ($rows as $row) {
if ($row['si-date'] > $actual_date AND $row['si-date'] < $selected_date) {
$selected_date = $row['si-date'];
$selected_row = $row;
}
}
if (is_array($selected_row)) {
// do your stuff your with the row
}
?>
如果您只需要获取今天之后的下一个日期,您可以参考这里解释得很好的 usort 函数,将最近的日期排在最前面:Sorting an array with DateTime strings?
以这种方式对数组进行排序后,您就可以处理该数组以找到比今天大的第一个日期。也许是这样的:
foreach($sorted_dates_array as $row){
//If the date is greater than the current time then return the row
if(strtotime($row['si-date'])>time())
{
return $row;
}
//There are no dates that are yet to be completed
return false;
}