2

这个问题似乎在谷歌出现了很多,我似乎仍然不知道如何做到这一点。

我正在做一个fetchAll,我得到一个对象或一个对象数组:

如果我 var_dump 它我得到:

array(3) {
  [0] object(Model_Model)#163 (55) {
    ['_name':protected] = NULL
    ['_info1':protected] = NULL
  }
  [1]  object(Talents_Model)#172 (55) {
    ['_name':protected] = NULL
    ['_info1':protected] = NULL
  }
  [2]object(Talents_Model)#143 (55) {

    ['_name':protected] = NULL
    ['_info1':protected] = NULL

  }

}

如果我这样做 $this->_helper->json( $the_object ); orjson_encode` 我得到空的 json 对象 [{},{},{},{}]

有没有办法将这些对象直接转换为 json,无论是一个对象还是它们的数组?

谢谢

我写了一些解决这个问题的东西:

public static function getProperties($object)
    {   
        $array = array();

        $reflection = new ReflectionObject($object);

        foreach($reflection->getProperties(ReflectionProperty::IS_PROTECTED) as $property)
        {  
            $property->setAccessible(TRUE);
            if(!$property->isStatic())
            { 
                $array[preg_replace('/_/', '', $property->getName(), 1)] = $property->getValue($object);
            }
        }

        if(empty($array)) return;

        return $array;
    }

这种方法可以更改为更通用,我也使用reflectionsnew inPHP 5.4

4

2 回答 2

3
$result=$this->fetchAll($select);
$result=$result->toArray();

我想,那么你应该使用 json_encode

于 2012-05-31T21:20:17.807 回答
2

您真正的问题不是 JSON 转换,而是对象成员不公开!

如果您知道属性名称,您应该能够轻松解决这个问题,或者如果您不知道(例如使用反射),则可以做更多的工作。

于 2012-05-31T21:17:18.360 回答