2015-11-26 78 views
2

我在我的项目中使用日历,我想从我的Event模型传递数据以查看JSON格式的文件。我尝试以下,但它没有工作,我不能够显示数据正常如何在Yii2中创建关联数组并将其转换为JSON?

$events = Event::find()->where(1)->all(); 

$data = []; 

foreach ($events AS $model){ 
    //Testing 
    $data['title'] = $time->title; 
    $data['date'] = $model->start_date; 
    $data['description'] = $time->description; 
} 

\Yii::$app->response->format = 'json'; 
echo \yii\helpers\Json::encode($data); 

但它仅在$data阵列返回一个模型,最终的数据应该是以下格式:

[ 
    {"date": "2013-03-19 17:30:00", "type": "meeting", "title": "Test Last Year" }, 
    { "date": "2013-03-23 17:30:00", "type": "meeting", "title": "Test Next Year" } 
] 

回答

4

当你这样写:渲染数据前

\Yii::$app->response->format = 'json'; 

,没有必要做任何额外的操作转换阵列JSON。

你只需要return(不echo)数组:

return $data; 

的数组将被自动转换为JSON。

此外它最好使用yii\web\Response::FORMAT_JSON常数而不是硬编码字符串。

的处理的另一种方法将使用ContentNegotiator滤波器,其具有更多的选项,允许多个动作的设定等示例控制器:

use yii\web\Response; 

... 

/** 
* @inheritdoc 
*/ 
public function behaviors() 
{ 
    return [ 
     [ 
      'class' => 'yii\filters\ContentNegotiator', 
      'only' => ['view', 'index'], // in a controller 
      // if in a module, use the following IDs for user actions 
      // 'only' => ['user/view', 'user/index'] 
      'formats' => [ 
       'application/json' => Response::FORMAT_JSON, 
      ],     
     ], 
    ]; 
} 

它也可以被配置成用于整个应用程序。

更新:如果你正在使用它控制之外,不设置响应格式。使用Json帮手encode()应该足够了。但也有你的一个代码错误,你应该这样创建新的数组:

$data = []; 
foreach ($events as $model) { 
    $data[] = [ 
     'title' => $time->title, 
     'date' => $model->start_date, 
     'description' => $time->description, 
    ]; 
} 
+0

其实不是这样。我试过,但没有工作,因为我需要以json格式回显输出,以便FrontPage上的插件可以显示它。 –

+1

@arogachev:很好解释!我不知道ContentNegotiator过滤器。谢谢:) – Chinmay

+1

@arogachev现在感谢你的工作, –

1

你可以尝试这样的:

$events = Event::find()->select('title,date,description')->where(1)->all() 
yii::$app->response->format = yii\web\Response::FORMAT_JSON; // Change response format on the fly 

return $events; // return events it will automatically be converted in JSON because of the response format. 

顺便说一句,你要覆盖$data变量foreach循环,你应该做:

$data = []; 
foreach ($events AS $model){ 
    //Make a multidimensional array 
    $data[] = ['time' => $time->title,'date' => $model->start_date,'description' => $time->description]; 
} 
echo \yii\helpers\Json::encode($data); 
+1

与我的回答有何不同?我提到了所有这些细节,甚至更多。 – arogachev