2015-11-26 20 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