我想分解一个日期,但想将默认索引0,1,2分别重命名为年、月、日,我试过了,但没能解决。以下是我现在正在做的事情。
$explode_date = explode("-", "2012-09-28");
echo $explode_date[0]; //Output is 2012
echo $explode_date[1]; //Output is 09
echo $explode_date[2]; //Output is 28
我想要什么
echo $explode_date['year']; //Output is 2012
echo $explode_date['month']; //Output is 09
echo $explode_date['day']; //Output is 28
谢谢。。
list($date['year'], $date['month'], $date['day']) = explode('-', '2012-09-28');
http://php.net/list
使用array_component:
$keys = array('year', 'month', 'day');
$values = explode("-", "2012-09-28");
$dates = array_combine($keys, $values);
list($year, $month, $day) = explode("-", "2012-09-28");
$x = compact('year', 'month', 'day');
var_dump($x);
array 'year' => string '2012' (length=4) 'month' => string '09' (length=2) 'day' => string '28' (length=2)
$explode_date = array (
'year' => $explode_date [0],
'month' => $explode_date [1],
'day' => $explode_date [2]
);
$explode_date = array();
list($explode_date['year'],$explode_date['month'],$explode_date['day']) = explode("-", "2012-09-28");
var_dump($explode_date);
您必须绘制出关联:
$explode_date = explode("-", "2012-09-28");
$new_array['year'] = $explode_date[0];
$new_array['month'] = $explode_date[1];
$new_array['day'] = $explode_date[2];
或者,您可以使用PHP的内置DateTime类(可能更好,因为您想要做的事情已经完成):
http://www.php.net/manual/en/book.datetime.php
$date = new DateTime('2012-09-28');
echo $date->format('Y');
echo $date->format('m');
echo $date->format('d');