开发者

PHP recursion stuck

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);
}


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}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜