简体   繁体   中英

rearranging values from array

My array

<?
    $date = array('16-01-14','16-01-28','16-02-14','16-02-28','16-03-14','16-03-28','16-04-14','16-04-28',
'16-05-14','16-05-28','16-06-14','16-06-28','16-07-14','16-07-28','16-08-14','16-08-28','16-09-14','16-09-28','16-10-14','16-10-28',
'16-11-14','16-11-28','16-12-14','16-12-28');
    $currentdate = date('y-m-d');

    ?>

Here is what my code looks like for selecting from the array the value however when it selects it from the array it doesn't format it into the correct format is there a way I can echo out the end date in the format like this mm/dd/yy instead of yy-mm-dd Thankyou.

<?php
$statement_date_timestamp = strtotime($statement_date);
$nextdate = "";
for($i = 0; $i<sizeof($date); $i++)
{
    if(strtotime($date[$i]) == $statement_date_timestamp)
        $nextdate = $date[$i+1];
}
echo'End Date:';
echo $nextdate;
?>

使用date()函数以所需的任何方式格式化时间戳记:

echo date('d/m/y', strtotime($nextdate));

使用输入格式和输入日期创建DateTime实例,然后转换为输出格式:

$nextdate = DateTime::createFromFormat('y-m-d', $nextdate)->format('m-d-y');

I think that all your code can be shortened:

$statement_date = date( 'y-m-d', strtotime( $statement_date ) );
$date_found     = array_search( $statement_date, $date );
$nextdate       = $date[$date_found+1];

echo date( 'm/d/y', strtotime($nextdate) );

I have used date() to format $statement_date because I don't know its format, but if it is ymd you can directly search for it.

array_search() return the corresponding key, then you obtain $nextdate incrementing key by 1.

To format $nextdate you can use date() or DateTime->format() , as per other answers.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM