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 オブジェクトを取得します [{},{},{},{}]

オブジェクトが1つでも配列でも、これらのオブジェクトを直接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 inも使用します。PHP 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 に答える