【问题标题】:how to convert a object in json data with zend framework?如何使用zend框架转换json数据中的对象?
【发布时间】:2012-06-06 04:03:05
【问题描述】:

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

我正在做一个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;
    }

这个方法可以改得更通用一些,我也用reflectionsPHP 5.4中的新方法

【问题讨论】:

    标签: php arrays json zend-framework object


    【解决方案1】:
    $result=$this->fetchAll($select);
    $result=$result->toArray();
    

    我想,那你应该使用json_encode

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 在我的设置中,受保护的属性不是问题。
    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2021-11-18
    • 2020-03-25
    相关资源
    最近更新 更多