簡體   English   中英

如何在Yii2中創建關聯數組並將其轉換為JSON?

[英]How to create associative array in Yii2 and convert to JSON?

我在項目中使用日歷,我想從Event模型傳遞數據以查看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" }
]

當您編寫此代碼時:

\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,
            ],                
        ],
    ];
}

也可以針對整個應用程序進行配置。

更新:如果要在控制器外部使用它,請不要設置響應格式。 結合使用帶有encode()方法的Json helper就足夠了。 但是代碼中也存在一個錯誤,您應該像這樣創建新的數組元素:

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

您可以這樣嘗試:

$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.

順便說一句,您正在覆蓋foreach循環中的$data變量,您應該這樣做:

$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM