2012-07-31 31 views
3

我正在開發PHP應用程序,其中我正在查詢數據庫並將生成的結果發送回html客戶端。PHP json_encode不與對象數組一起工作

目前我正在使用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" 
     } 
    } 
    } 
} 

和編碼它示出,而不是JSON空之後。 我需要序列化它嗎?任何建議都將是可觀的。 感謝你。

+0

類似的東西:http://stackoverflow.com/questions/6836592/serializing-php-object-to-json – MarcDefiant 2012-07-31 12:43:29

回答

11

它看起來像所有的「ProductComment」屬性是私有的,所以當它涉及到JSON編碼,你會得到:

[{}, {}] 

這基本上是一個數組,在兩個空的對象它。

你需要做的是告訴PHP在序列化(或json編碼)時哪些屬性可以並且應該保留。爲此,你想添加__sleep()神奇的方法到你的班級:(http://uk.php.net/__sleep

+0

謝謝丹。你的權利。我的產品評論屬性是私人的,現在我變成了公衆,現在它的工作就像魔術一樣。謝謝你的回答。 :) – ashutosh 2012-07-31 12:45:14

+2

哈哈我是個白癡。做了同樣的錯誤,並瀏覽了Stackoverflow。嘗試了一切,直到我意識到我的所有對象屬性都是私有的。DOH!謝謝你..你提醒我我的死亡率:) – Spock 2013-09-05 12:30:38