【问题标题】:PHP json_encode not working with array of objectsPHP json_encode 不适用于对象数组
【发布时间】:2012-07-29 05:25:35
【问题描述】:

我正在开发 php 应用程序,我在其中查询数据库并将生成的结果发送回 html 客户端。

目前我正在使用 php 函数 json_encode 获取我在 JSON 中编码的对象数组。

但在编码后,我的结果中出现了空数组。

以下结构是在编码为 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。 我需要序列化它吗? 任何建议都将是可观的。 谢谢。

【问题讨论】:

标签: php arrays serialization json


【解决方案1】:

看起来“ProductComment”的所有属性都是私有的,所以当涉及到 JSON 编码时,你会得到:

[{}, {}]

这基本上是一个数组,里面有两个空对象。

您需要做的是告诉 PHP 在序列化(或 json 编码)时可以并且应该保留哪些属性。为此,您想将 __sleep() 魔术方法添加到您的类中:(http://uk.php.net/__sleep)

【讨论】:

  • 谢谢丹。你的权利。我的 ProductComment 属性是私有的,现在我改为公共的,现在它像魔术一样工作。!!!!!!谢谢解答。!!! :)
  • 哈哈,我是个白痴。犯了同样的错误并浏览了Stackoverflow。尝试了一切,直到我意识到我所有的对象属性都是私有的.. DOH!谢谢人..你让我想起了我的死亡:)
猜你喜欢
  • 2015-05-03
  • 2013-11-28
  • 2018-10-10
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 2014-01-27
  • 2021-12-13
相关资源
最近更新 更多