PHP 5.3 从关联数组中回显日期对象?
我想在数据库查询后回显日期列的结果,但如果我在尝试回显变量之前在 $array 上调用 var_dump,则该字符串只会回显到屏幕。
如果我取消注释“//var_dump($assocArray[0]["date"]);”然后我可以回显日期,否则什么都不会回显......这里发生了什么事?
$link = sqlsrv_connect("localhost", array("UID" => 'myuser', "PWD" => 'mypass', "Database"=>'mydb'));
$result = sqlsrv_query($link, "select date from mytable where id=1");
$i=0;
while($row=sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC))
{
$assocArray[$i] = $row;
$i++;
}
sqlsrv_free_stmt($result);
sqlsrv_close($link);
echo "\n Dump AssocArray: \n";
echo "====================\n";
//var_dump($assocArray[0]["date"]);
echo "\n\n Echo Date: \n";
echo "====================\n";
echo $assocArray[0]["date"]->date; //doesnt print
echo "\n\n Dump Date: \n";
echo "====================\n";
var_dump($assocArray[0]["date"]);
/* result of Dump Date:
object(DateTime)#1 (3) {
["date"]=>
string(19) "2011-01-20 04:00:00"
["timezone_type"]=>
int(3)
["timezone"]=>
string(28) "America/Indiana/Indianapolis"
}
*/
I want to echo the result from a date column after a database query, but the string will only echo to the screen if I call var_dump on the $array before I try to echo the variable.
If I uncomment "//var_dump($assocArray[0]["date"]);" then I can echo the date, otherwise nothing will be echoed...what is going on here?
$link = sqlsrv_connect("localhost", array("UID" => 'myuser', "PWD" => 'mypass', "Database"=>'mydb'));
$result = sqlsrv_query($link, "select date from mytable where id=1");
$i=0;
while($row=sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC))
{
$assocArray[$i] = $row;
$i++;
}
sqlsrv_free_stmt($result);
sqlsrv_close($link);
echo "\n Dump AssocArray: \n";
echo "====================\n";
//var_dump($assocArray[0]["date"]);
echo "\n\n Echo Date: \n";
echo "====================\n";
echo $assocArray[0]["date"]->date; //doesnt print
echo "\n\n Dump Date: \n";
echo "====================\n";
var_dump($assocArray[0]["date"]);
/* result of Dump Date:
object(DateTime)#1 (3) {
["date"]=>
string(19) "2011-01-20 04:00:00"
["timezone_type"]=>
int(3)
["timezone"]=>
string(28) "America/Indiana/Indianapolis"
}
*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来
$assocArray[0]["date"]
是一个DateTime
对象。要获取日期,您需要使用
format()
。It seems
$assocArray[0]["date"]
is aDateTime
object.To get the date, you need to use
format()
.$date = $assocArray["date"]->format('Ymd H:i:s');
这对我来说很完美
$date = $assocArray["date"]->format('Y-m-d H:i:s');
This one worked Perfect for me