php- 如何为此代码创建循环
php- How to create a loop for this code
如何对以下代码部分使用循环(for、forEach、while 等)。
这里 "tarray" 是一个包含 10 个值的数组。
代码部分:
$string = $tarray[0];
$datetime = strtotime($string);
$datetime1 = date("Y-m-d H:i:s", $datetime);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);
$string = $tarray[1];
$datetimea = strtotime($stringa);
$datetime2 = date("Y-m-d H:i:s", $datetimea);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime2);
我只想写一次而不是声明多个变量。
像这样使用 foreach 循环:
$arr = ['Hello', 'world', 'John'];
foreach($arr as $string) {
echo $string;
}
所以在你的情况下:
foreach($tarray as $string) {
$datetime = strtotime($string);
$datetime1 = date("Y-m-d H:i:s", $datetime);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);
}
我想你想要这样:-
$date_array = [];
foreach($tarray as $tar){
$datetime1 = date("Y-m-d-H-i-s",strtotime($tar));
$date_array[] = array_combine(['year', 'month', 'day', 'hours', 'minutes', 'seconds'], explode('-', $datetime1));
}
演示输入:- https://eval.in/897154
注意:- 您也可以在那里使用 list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);
,没有任何问题。
演示输出:-https://eval.in/897156
如何对以下代码部分使用循环(for、forEach、while 等)。 这里 "tarray" 是一个包含 10 个值的数组。 代码部分:
$string = $tarray[0];
$datetime = strtotime($string);
$datetime1 = date("Y-m-d H:i:s", $datetime);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);
$string = $tarray[1];
$datetimea = strtotime($stringa);
$datetime2 = date("Y-m-d H:i:s", $datetimea);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime2);
我只想写一次而不是声明多个变量。
像这样使用 foreach 循环:
$arr = ['Hello', 'world', 'John'];
foreach($arr as $string) {
echo $string;
}
所以在你的情况下:
foreach($tarray as $string) {
$datetime = strtotime($string);
$datetime1 = date("Y-m-d H:i:s", $datetime);
list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);
}
我想你想要这样:-
$date_array = [];
foreach($tarray as $tar){
$datetime1 = date("Y-m-d-H-i-s",strtotime($tar));
$date_array[] = array_combine(['year', 'month', 'day', 'hours', 'minutes', 'seconds'], explode('-', $datetime1));
}
演示输入:- https://eval.in/897154
注意:- 您也可以在那里使用 list($year, $month, $day, $hours, $minutes, $seconds) = explode('-', $datetime1);
,没有任何问题。
演示输出:-https://eval.in/897156