如何json编码多行数据

时间:2013-01-05 05:38:00

标签: php json

我在yii工作。我正在拥有存储信息及其相关日期的表。在以下功能中,我通过提供日期作为输入来搜索信息。我在控制器中有功能 -

     public function actionGetHistoryContent()
      {
        $content1=new Dnycontenttitle();
        $content1->date="2013-01-01";
        $getcontentId=Dnycontenttitle::model()-   >indAllByAttributes(array("date"=>$content1->date));

        foreach ($getcontentId as $Id)
        {

         //echo $Id->contentTitleId;
         $getcontent=Dnycontent::model()->findAllByAttributes(array("contentTitleId"=>$Id->contentTitleId));
         foreach($getcontent as $content)
         {  
            echo "</br>".$content->content;
         }

      }  
     echo "{'Historys':    [".CJSON::encode(array("contentId"=>$Id>contentTitleId,"Intro"=>$content->content))."] }";
}

因此上述功能正在检索日期为“2013-01-01”的所有信息行。我想以json格式将所有这些数据发送到客户端。但是上面的json只发送一行数据,最后由函数检索。 例如假设上面的函数从表中检索2行数据=

contentId = 1 intro =“今天是星期日”日期= 2013-01-01      contentId = 23 intro =“世界的微笑日”日期= 2013-01-01

但是当我通过json发送它时,它只发送最后检索到的contentId = 23的信息。 那么如何以json格式发送多行数据。

1 个答案:

答案 0 :(得分:0)

你必须在foreach()中做到这一点。否则你会得到最后一个元素.. 试试这个。

public function actionGetHistoryContent()
  {
    $content1=new Dnycontenttitle();
    $content1->date="2013-01-01";
    $getcontentId=Dnycontenttitle::model()-   >indAllByAttributes(array("date"=>$content1->date));
    foreach ($getcontentId as $Id)
     {
     $getcontent=Dnycontent::model()->findAllByAttributes(array("contentTitleId"=>$Id->contentTitleId));
     foreach($getcontent as $content)
     {  
        echo "</br>".$content->content;
        echo "{'Historys':    [".CJSON::encode(array("contentId"=>$Id>contentTitleId,"Intro"=>$content->content))."] }";
     }
  }  

}

相关问题