Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Symfony1 symfony-从操作中的对等方法调用返回JSON_Symfony1_Propel - Fatal编程技术网

Symfony1 symfony-从操作中的对等方法调用返回JSON

Symfony1 symfony-从操作中的对等方法调用返回JSON,symfony1,propel,Symfony1,Propel,我有一些代码检查一个参数,并调用一个对等方法从数据库中获取项目 我需要得到的是JSON中的这些项目 我的同伴方法如下: public static function searchFromRequest($word) { $c = new Criteria(); $c->addJoin(self::ARTICLE_ID, ArticlePeer::ID); $c->add(self::TITLE, '%'.$word.'%', Criteria::LIKE);

我有一些代码检查一个参数,并调用一个对等方法从数据库中获取项目

我需要得到的是JSON中的这些项目

我的同伴方法如下:

public static function searchFromRequest($word)
{
    $c = new Criteria();
    $c->addJoin(self::ARTICLE_ID, ArticlePeer::ID);
    $c->add(self::TITLE, '%'.$word.'%', Criteria::LIKE);
    $c->addAnd(self::ARTICLE_ID, null, Criteria::ISNOTNULL);
    $c->addAscendingOrderByColumn(self::TITLE);
    return self::doSelect($c);
}
我的行动是:

public function executeSearch()
{
    $this->word = $this->getRequestParameter('word');
    $this->content_type = $this->getRequestParameter('content_type');
    if($this->content_type == 'article')
    {
        $words = ItemPeer::searchFromRequest($this->word);
    }
    else
    { 
       echo "Nothing here";
    }
我可以
var\u dump($words)
并获得一个项目数组(集合)。问题是,如何返回JSON中的所有项

我试过使用:

        $this->getResponse()->setHttpHeader('Content-type', 'application/json');
        $words = ItemPeer::searchFromArticleRequest($this->word);
        return $this->renderText(json_encode($words));
但这只是返回空JSON括号的加载:
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]


谢谢

json_encode/json_decode只能对PHP数组进行编码/解码,而不能对对象进行编码/解码。变量

$words
将是项对象的数组,这就是您编写输出的原因

基本上有两种解决方案。您可以编写自己的用于对象的json编码器,如这里的第一条注释:

或者编写一个函数,将项目对象转换为PHP数组,如下所示:


似乎
json\u encode()
不喜欢构建推进对象的方式

另一种解决方案是使用
XXXPeer::doSelectStmt()


您还可以对对象调用
toArray()

$words = ItemPeer::searchFromArticleRequest($this->word);
$wordsArray = array();
foreach ($words as $word)
{
    $wordsArray[] = $word->toArray();
}
return $this->renderText(json_encode($wordsArray));
用于单个对象或整个对象集合。

1.6:

  • object->toJSON()
  • 集合->导出到('JSON')
是的,我比我更喜欢你的解决方案:)你使用的是哪种版本的Propel和Symfony?@Jan Fabry我使用的是Symfony 1.4和Propel 1.4,我找到了单个对象的toJSON()方法,但没有找到整个集合的方法。如何序列化集合?UPD Ooops,就是它--exportTo('JSON')。
$words = ItemPeer::searchFromArticleRequest($this->word);
$wordsArray = array();
foreach ($words as $word)
{
    $wordsArray[] = $word->toArray();
}
return $this->renderText(json_encode($wordsArray));