php递归卡住了

时间:2011-07-30 00:55:32

标签: php recursion

我试图通过一个多维的对象/数组结构进行递归来创建json,但是以下不起作用。$ data被重置,但我不知道如何防止这种情况。

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

1 个答案:

答案 0 :(得分:2)

如果你正在尝试学习递归这是一回事,但至少对我来说,json_encode会自动地对对象和数组进行递归编码,因此没有必要编写额外的函数。

使用此代码进行测试:

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}}
相关问题