0

When the JSON format is response, the original sorting of the data is lost. When response in XML, the sort is saved. How can I preserve the original sorting with JSON?

My controller:

use yii\rest\ActiveController;

class  DomainController extends ActiveController
{
    ...
    public function behaviors()
    {
      $behaviors = parent::behaviors();
      $behaviors['corsFilter' ] = [
          'class' => \yii\filters\Cors::className(),
      ];

      $behaviors['contentNegotiator'] = [
        'class' => \yii\filters\ContentNegotiator::className(),
        'formats' => [
            'application/json' => \yii\web\Response::FORMAT_JSON,
        ],
      ];

      return $behaviors;
    }

And action in the controller:

public function actionIndex()
{
    $domains =  Domain::find()
        ->leftJoin('WEB_DOMAIN_PRIORITY', 'WEB_DOMAIN_PRIORITY.id = WEB_DOMAIN.priority_id')
        ->orderBy(['priority' => SORT_DESC])->all();

    $test = [];

    foreach ($domains as $domain) {
        $test[$domain->id] = $domain->title;
    }
    //echo "<pre>"; print_r($test);die;  < -- its ok. right sort
    //return $test;                      < -- its wrong. sort is changed
}

And if i change in behavior this:

'application/json' => \yii\web\Response::FORMAT_JSON,

To:

'application/json' => \yii\web\Response::FORMAT_XML,

I have xml response with right sort.

Only JSON response sorting my array by array keys(ASC).

2 Answers 2

1

Here

$test[$domain->id] = $domain->title; 

you are adding new array keys. This could change order based on rest/Serializer.

You could apply preserveKeys to serializer as here http://www.yiiframework.com/doc-2.0/yii-rest-serializer.html#$preserveKeys-detail or don't change keys order.

Sign up to request clarification or add additional context in comments.

Comments

0

@Fabrizio Caldarelli not exactly. In this moment response preparing JsonResponseFormatter and it use yii\helpers\Json::encode for format data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.