【问题标题】:How do I format a list of dates from an array of unix timestamps?如何格式化来自 unix 时间戳数组的日期列表?
【发布时间】:2014-11-12 05:28:10
【问题描述】:

我正在使用的 WordPress 插件正在输出一个数组(应该只有两个日期/时间),如下所示:

Array ( [0] => 1412037900 [1] => 1413340200 [2] => )

我不确定为什么会有一个尾随的空节点,但无论如何,我都试图从中获取格式化日期/时间的列表。

我的 php 中有这个(get_post_meta 函数正在返回数组):

<?php global $post;
$date = get_post_meta( $post->ID, '_cmb2_date_time', true );
foreach ( $date as $item ) {
echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
} ?>

现在我得到了这个:

September 30, 2014, 12:45 am
October 15, 2014, 2:30 am
January 1, 1970, 12:00 am

而我想要的是这样的:

September 30, 2014, 12:45 am
October 15, 2014, 2:30 am

最后,我还想让它成为有条件的,以便在没有日期时回显“TBA”。一旦它工作,我可以稍后再担心,但当数组为空时,我收到一条错误消息,提示“警告:为 foreach() 提供的参数无效...”

任何帮助将不胜感激!

【问题讨论】:

  • 只使用 if else,如果不为空,使用 foreach,否则 echo TBA

标签: php arrays wordpress timestamp unix-timestamp


【解决方案1】:

最后一个结果是 0 unix 时间的日期时间等值,因为数组末尾有一个空对象。只需在转换之前删除(弹出)最后一个对象,如下所示:

<?php global $post;
$date = get_post_meta( $post->ID, '_cmb2_date_time', true );
array_pop($date);
foreach ( $date as $item ) {
echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
} ?>

然后,包含 TBA 功能:

<?php global $post;
$date = get_post_meta( $post->ID, '_cmb2_date_time', true );
//If you are still getting an extra object even when there are no dates to be passed 
//from get_post_meta then pop before the check if empty
array_pop($date);
if( empty( $date ) )
{
     echo '<p>TBA</p>';
}
else
{
    //If you are not getting the extra object when empty, only when there are results
    //then put the pop here before the foreach loop
    foreach ( $date as $item ) {
        echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
    } 
}
?>

【讨论】:

  • array_pop 返回数组的最后一个值。只需使用 array_pop($date),不要为其分配变量。
  • 这很好用,谢谢大家!!我确实需要将 pop 移到 foreach 一侧,但之后它就完全符合我的需要了。
【解决方案2】:

date()如果最后一个参数为空(如果为0则输出unix epoch)将输出当前日期和时间,因此使用此代码;

foreach ( $date as $item ) {
    if($item) echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
}

如果数组条目为空,则不会回显日期。

希望这会有所帮助。

【讨论】:

  • 谢谢,worldofjr!这个与整个数组完美配合,但当数组为空时,它仍然给我“无效”的 foreach 错误。
  • 您可以通过在填充它之前声明一个空数组来解决这个问题(或者视情况不填充它)。即$date = array();。如果您从其他来源获取数据,这无论如何都是一个好习惯。请记住通过单击旁边的勾号来选择最佳答案。
【解决方案3】:

将 foreach 更改为

foreach ( $date as $item ) {
    echo '<p>'.(empty($item)?"TBA":date("F j, Y, g:i a", (int)$item)).'</p>';
} 

【讨论】:

  • 感谢您的快速回答,kums,但是这个输出两个日期,然后在列表末尾输出 TBA 代替 unix 日期。
猜你喜欢
  • 2012-08-13
  • 1970-01-01
  • 2011-03-23
  • 2012-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-26
相关资源
最近更新 更多