Mohan Prasad
Mohan Prasad

Reputation: 682

Yii2 Array sorting

In my Yii2 Project I have an array for example

$array = [];    
$array [] = 8 , 3, 6

So when I print out the array is

[8,3,6]

So when I use the same in a where statement it jumbles up.

$class = ModelClass::find()->where(['array_no' => $array])->all

So when I print out class I get the output in asc order sorted.. I get the information of

How can i stop this from happening. I want them to return my output in the same order as array

Upvotes: 2

Views: 1134

Answers (1)

soju
soju

Reputation: 25302

You should use ORDER BY FIELD(), e.g. :

$models = ModelClass::find()
  ->where(['array_no' => $array])
  ->orderBy(new \yii\db\Expression('FIELD (array_no, '.implode(',', $array).')'))
  ->all();

Upvotes: 3

Related Questions