PHP json_encode not working with array of objects

12,847

It looks like all of the properties of "ProductComment" are private, so when it comes to JSON-encoding, you'd get:

[{}, {}]

Which is basically an array, with two empty objects in it.

What you need to do is tell PHP which properties can and should be kept when serializing (or json encoding). For that, you want to add the __sleep() magic method to your class: (http://uk.php.net/__sleep)

Share:
12,847

Related videos on Youtube

ashutosh
Author by

ashutosh

Updated on September 15, 2022

Comments

  • ashutosh
    ashutosh over 1 year

    I am developing php application in which i am querying database and the generated result I am sending back to html client.

    Currently I am getting array of objects which I am encoding in JSON using php function json_encode.

    But after encoding I am getting null array in my result.

    The following structure is before encoding to 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"
          }
        }
      }
    }
    

    And after encoding it showing null instead of JSON. Do i need to serialize it? Anything advice will be appreciable. Thanking you.

  • ashutosh
    ashutosh over 11 years
    Thanks Dan. Your Right. My ProductComment properties are private and now i changed to public, now its working like magic.!!!! Thanks for answer.!!! :)
  • Spock
    Spock over 10 years
    Lol I'm an idiot. Did the same mistake and browsed Stackoverflow. Tried EVERYTHING until I realized all my object properties were private.. DOH!! Thanks man.. you reminded me of my mortality :)