简体   繁体   English

将个别格式化的 output 参数分配到变量(或数组)中 - PHP

[英]assign individual formatted output parameters into variables (or array) - PHP

I have the output of a time difference displayed using the following code:我使用以下代码显示时差的 output:

$interval = $timenow->diff($datatime);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');

An example displayed output is:显示的示例 output 是:

0 years 0 months 2 days 9 hours 22 minutes 46 seconds

I would like to assign the individual values displayed into variables so as to do some calculations on those variables.我想将显示的各个值分配给变量,以便对这些变量进行一些计算。 (I don't only just want to display the values), I would like to assign, say: $years = y, $months = m, and so on, so that I can work with the year, month, minutes and seconds as variables. (我不只是想显示值),我想分配,比如:$years = y, $months = m,等等,这样我就可以处理年、月、分和秒作为变量。

How might I do this?我该怎么做?

I would simply format your variable into individual variables like so:我会简单地将您的变量格式化为单个变量,如下所示:

$dateTime = new DateTime(); // Any DateTime object, this is using the current date and time as an example. 

$year = $dateTime->format('Y');
$month = $dateTime->format('m');
$hour = $dateTime->format('h');
$minute = $dateTime->format('i');
$second = $dateTime->format('s');

There is no need to create the variables manually.无需手动创建变量。 All these values are already available to you inside your $interval object.$interval object 中,您已经可以使用所有这些值。 The DateInterval class (which is the return type of diff ) specifies properties: DateInterval class (它是diff的返回类型)指定属性:

/* Properties */
public int $y ;
public int $m ;
public int $d ;
public int $h ;
public int $i ;
public int $s ;
public float $f ;
public int $invert ;
public mixed $days ;

where $y , $m , $d , $h , $i and $s hold the values you need (from years to seconds).其中$y$m$d$h$i$s保存您需要的值(从几年到几秒)。 Thus, you can simply evoke the property you need (for example, $interval->m to get the months value).因此,您可以简单地调用您需要的属性(例如, $interval->m来获取月份值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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