Php 如何使用zend framework转换json数据中的对象?
这个问题似乎在谷歌上经常出现,而我似乎仍然没有掌握如何做到这一点 我正在执行一个Php 如何使用zend framework转换json数据中的对象?,php,arrays,json,zend-framework,object,Php,Arrays,Json,Zend Framework,Object,这个问题似乎在谷歌上经常出现,而我似乎仍然没有掌握如何做到这一点 我正在执行一个fetchAll,然后返回一个对象或一组对象: 如果我把它扔掉,我会得到: array(3) { [0] object(Model_Model)#163 (55) { ['_name':protected] = NULL ['_info1':protected] = NULL } [1] object(Talents_Model)#172 (55) { ['_name':prot
fetchAll
,然后返回一个对象或一组对象:
如果我把它扔掉,我会得到:
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->\u helper->json($u对象)或
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;
}
这个方法可以更改为更通用一点,我还使用了
PHP5.4中的reflections
new
您真正的问题不是JSON转换,而是对象成员不是公共的
如果您知道属性名称,您应该能够轻松地解决这个问题,如果您不知道属性名称,则需要做更多的工作(例如,使用反射)
我想,那么您应该在我的设置中使用json_encode受保护的属性没有问题。方法
toArray()
在哪里?toArray是一个zend方法,看起来不推荐使用,但可能有用
$result=$this->fetchAll($select);
$result=$result->toArray();