我正在开发php应用程序,在该应用程序中查询数据库,并将生成的结果发送回html客户端。
目前,我正在使用php函数JSON_encode在JSON中编码对象数组。
但在编码之后,我的结果中得到了null数组。
以下结构是在编码为JSON 之前
array(2) {
[0]=>
object(ProductComment)#6 (2) {
["_productId":"ProductComment":private]=>
string(1) "1"
["_commentArray":"ProductComment":private]=>
array(2) {
[0]=>
array(3) {
["comment"]=>
string(9) "comment 1"
["creationDate"]=>
string(19) "2000-02-02 00:00:00"
["userName"]=>
string(8) "Ashutosh"
}
[1]=>
array(3) {
["comment"]=>
string(13) "comment1 text"
["creationDate"]=>
string(19) "2012-07-31 10:20:27"
["userName"]=>
string(8) "Ashutosh"
}
}
}
[1]=>
object(ProductComment)#5 (2) {
["_productId":"ProductComment":private]=>
string(1) "2"
["_commentArray":"ProductComment":private]=>
array(2) {
[0]=>
array(3) {
["comment"]=>
string(22) "comment2 product2 text"
["creationDate"]=>
string(19) "2012-07-31 10:48:06"
["userName"]=>
string(8) "Ashutosh"
}
[1]=>
array(3) {
["comment"]=>
string(22) "comment2 product4 text"
["creationDate"]=>
string(19) "2012-07-31 10:48:14"
["userName"]=>
string(8) "Ashutosh"
}
}
}
}
编码后显示null而不是JSON。我需要序列化它吗?任何建议都是值得赞赏的。谢谢你。
看起来"ProductComment"的所有属性都是私有的,所以当涉及到JSON编码时,您会得到:
[{}, {}]
它基本上是一个数组,里面有两个空对象
您需要做的是告诉PHP在序列化(或json编码)时可以和应该保留哪些属性。为此,您需要将__sleep()
魔术方法添加到您的类中:(http://uk.php.net/__sleep)