在某些场景中,索引数组的键可作为id,但是返回索引数组json序列化之后也会是json数组,最终想要的是却是json对象(当然也可以返回数组,接收端自行遍历将索引作为id)。
正常设置json形式的返回结果:
<?php$response = Yii::$app->getResponse();$response->format = $response::FORMAT_JSON;
php中实现索引数组转为json对象的方式为 json_encode($arr, JSON_FORCE_OBJECT);,其中 JSON_FORCE_OBJECT 是关键,那么如何让yii2也可以实现?
<?php$response = Yii::$app->getResponse();$response->format = $response::FORMAT_JSON;// 此配置将会覆盖defaultFormatters的默认配置$response->formatters = [// json对应的内容,将其encodeOptions$response::FORMAT_JSON => ['class' => 'yii\web\JsonResponseFormatter','encodeOptions' => JSON_FORCE_OBJECT]];
