PHP json_encode无法处理对象数组

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP json_encode无法处理对象数组脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发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)

脚本宝典总结

以上是脚本宝典为你收集整理的PHP json_encode无法处理对象数组全部内容,希望文章能够帮你解决PHP json_encode无法处理对象数组所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。