这个问题似乎在谷歌出现了很多,我似乎仍然不知道如何做到这一点。
我正在做一个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 ); or
json_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;
}
这种方法可以更改为更通用,我也使用reflections
new inPHP 5.4