使用 zend json 从 findby 查询将学说结果集转换为 json

convert doctrine resultset to json from findby query using zend json

我在使用 findBy 查询时但是转换数据的所有方面都得到了很多帮助。

我想要的是此查询的结果集的 json 字符串,确保对象被序列化,以便我可以在其他地方使用它:

$posts = $entityManager->getRepository(\Application\Entity\Post::class)
        ->findBy(['status'=>\Application\Entity\Post::STATUS_PUBLISHED],
            ['dateCreated'=>'DESC']);  

Json::encode($posts,true) 来自 Zend Framework Json 但是当我这样做时数据没有显示。

结果将是一个 json 编码的字符串,其中包含我可以传递到其他地方的实体对象

我将用于解码:

\Zend\Json\Decoder::decode($posts,\Zend\Json\Json::TYPE_OBJECT)

除非我应该使用 \Zend\Json\Json::TYPE_ARRAY)

这是我的做法:

包括:use Zend\Json\Json;

这是我的函数/动作示例:

public function getListAction(){
        $request   = $this->getRequest();
        if($request->isPost()){
            // recuperer le produit choisi :
            $element = $request->getPost("element");
            $result = null;
            $result = $this->getEntityManager()->getRepository('Application\Entity\Element')->findBy(array('etat' => 'valide' , 'pkElement' => $element));
            $champs = array();
            $i = 0;
            foreach ($result as $value) {
                $champs[$i] = array("id"=>$value->getPkElement() , "nom"=>$value->getNom());
                $i++;
            }
            $data = array(
                'result' => true,
                'data' => $champs
            );
            return $this->getResponse()->setContent(Json::encode($data));
        }
    }

然后在view.phtml中调用:

$.post('/application/controller_name/getList', {element: $("select[name=element]").val()}, function(result) {
            var options = $("select[name=element]");
            var obj = JSON.parse(result);
            var data = obj.data;
            var selected = "";
            options.empty();
            for (var i = 0; i < data.length; i++) {
               options.append($("<option />").val(data[i]['id']).text(data[i]['nom']));
            }
        });

希望对您有所帮助。