Yii2-如何强制响应JSON格式化程序使用对象而不是数组?

The*_*der 4 php json httpresponse yii yii2

我知道可以设置,Yii::$app->response->format = \yii\web\Response::FORMAT_JSON但是如何设置JSON编码标志,JSON_FORCE_OBJECT以便将所有数组都编码为对象?

The*_*der 5

好吧,这并不难:

Yii::$app->response->formatters[\yii\web\Response::FORMAT_JSON] = [
    'class' => 'yii\web\JsonResponseFormatter',
    'encodeOptions' => JSON_FORCE_OBJECT,
];
Run Code Online (Sandbox Code Playgroud)

甚至单线:

Yii::$app->response->formatters[\yii\web\Response::FORMAT_JSON]['encodeOptions'] = JSON_FORCE_OBJECT;
Run Code Online (Sandbox Code Playgroud)