0

I am trying to recurse through a multidimensional Object/Array structure to create JSON, but the following isn't working. $data is reset, but I'm not sure how to prevent this.

public function encodeJSON($data) {
    foreach ($data as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $json->$key = $this->encodeJSON($value);
        } else {
            $json->$key = $value;
        }
    }
    return json_encode($json);
}
4
  • While your thought process is a little off so this doesn't actually create valid JSON, it does recurse, and $data is not reset. It produces one string with all of the values including nested arrays. I tested it on several arrays. Commented Jul 30, 2011 at 1:00
  • As a side note: encoding values individually will produce incorrect JSON! You'll end up with something like {"foo":"{\"bar\":\"baz\"}"} instead of the intended {"foo":{"bar":"baz"}}. You need to encode the whole object/array at once. Commented Jul 30, 2011 at 1:02
  • 3
    @Dan - Exactly. I'm not really sure what mike628 is trying to do here. Mike - what's wrong with the return value of json_encode($data);? json_encode() is perfectly capable of serializing arrays and objects! Commented Jul 30, 2011 at 1:03
  • I am trying to json_encode an object structure that includes private members. So, I am trying to take it out of the object and encode it. My test data is this:stackoverflow.com/questions/6878141/json-encode-missing-data Commented Jul 30, 2011 at 13:34

1 Answer 1

2

If you're trying to learn recursion that's one thing, but at least for me json_encode automatically encodes objects and arrays recursively so it's not really necessary to write the extra function.

Tested with this code:

class TestClass {
    var $c1;
    var $c2;

    function __construct() {
        $this->c1 = 'member variable 1';
        $this->c2 = 8080;
    }
}

$test = array('hello' => 'world', 'age' => 30,
    'arr' => array('a' => 'b', 'c' => 'd'), 'obj' => new TestClass());

echo(json_encode($test));
// I get the following JSON object:
// {"hello":"world","age":30,"arr":{"a":"b","c":"d"},"obj":{"c1":"member variable 1","c2":8080}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.