在某些场景中,索引数组的键可作为id,但是返回索引数组json序列化之后也会是json数组,最终想要的是却是json对象(当然也可以返回数组,接收端自行遍历将索引作为id)。

    正常设置json形式的返回结果:

    1. <?php
    2. $response = Yii::$app->getResponse();
    3. $response->format = $response::FORMAT_JSON;

    php中实现索引数组转为json对象的方式为 json_encode($arr, JSON_FORCE_OBJECT);,其中 JSON_FORCE_OBJECT 是关键,那么如何让yii2也可以实现?

    1. <?php
    2. $response = Yii::$app->getResponse();
    3. $response->format = $response::FORMAT_JSON;
    4. // 此配置将会覆盖defaultFormatters的默认配置
    5. $response->formatters = [
    6. // json对应的内容,将其encodeOptions
    7. $response::FORMAT_JSON => [
    8. 'class' => 'yii\web\JsonResponseFormatter',
    9. 'encodeOptions' => JSON_FORCE_OBJECT
    10. ]
    11. ];