Patrioticcow
Patrioticcow

Reputation: 27048

how to convert a object in json data with zend framework?

this question seems to come up a lot in google and i still dont seem to get a grasp on how to do this.

i am doing a fetchAll and i get back either a object or a array of objects:

if i var_dump it i get:

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

  }

}

if i do $this->_helper->json( $the_object );orjson_encode` i get empty json objects [{},{},{},{}]

is there a way of converting those objects into json directly, no matter if there is one object or a array of them?

thanks

i write something that solver this problem:

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

this method can be changed to be a bit more generic and i also use reflections new in PHP 5.4

Upvotes: 2

Views: 3116

Answers (2)

Mert Emir
Mert Emir

Reputation: 691

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

I think, then you should use json_encode

Upvotes: 3

J.C. Inacio
J.C. Inacio

Reputation: 4472

Your real issue is not the JSON conversion, is that the object members are not public!

You should be able to work around this easily if you know the attribute names, or with a bit more work if you don't (using reflection, for instance).

Upvotes: 2

Related Questions