2012-07-13 108 views
1

我想爆炸一个日期,但想要将默认索引0,1,2分别重命名为year,month,day,我试过但我无法弄清楚。这就是我们现在正在做的事情。在PHP中重命名数组索引

$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 

谢谢..

+0

可能重复:http://stackoverflow.com/questions/240660/in-php-how-do-you-change-the-key-of-an-array-element – sed 2012-07-13 09:12:36

+0

@ V413HAV您可能希望查看PHP的DateTime类(内置),因为它可以优雅地处理日期和时间。它也受到PHP的支持,为什么不使用已经构建的东西,而不是重新发明轮子? – Stegrex 2012-07-13 09:25:26

+0

@Stegrex正如我告诉complex857我需要PHP版本<5的解决方案,并且由于OOP不太好;)仍然需要学习它。 – 2012-07-13 09:29:42

回答

0
$explode_date = array (
    'year' => $explode_date [0], 
    'month' => $explode_date [1], 
    'day' => $explode_date [2] 
); 
1
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) 
6

使用array_combine

$keys = array('year', 'month', 'day'); 
$values = explode("-", "2012-09-28"); 
$dates = array_combine($keys, $values); 
+0

伟大的1,所以+1这个,它很容易,但我想php版本 2012-07-13 09:22:42

0
$explode_date = array(); 
list($explode_date['year'],$explode_date['month'],$explode_date['day']) = explode("-", "2012-09-28"); 

var_dump($explode_date); 
0

你必须绘制出协会:

$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');