A
A
alysenko2017-01-25 19:30:08
Yii
alysenko, 2017-01-25 19:30:08

How to sort an array in Yii2 using ArrayHelper?

There is an array.

$array = [
  [
    'name' => 'name1',
    'status' => 1,
    'year' => 21
  ],
  [
    'name' => 'name2',
    'status' => 0,
  ],
  [
    'name' => 'name3',
    'status' => 0,
  ],
  [
    'name' => 'name4',
    'status' => 0,
    'year' => 30
  ],
  [
    'name' => 'name5',
    'status' => 0,
    'year' => 25
  ],
]

Task. You need to use ArrayHelper in Yii2 to sort this array by "year" (both ascending and descending) in such a way that:
  • user with status 1 was always first
  • users with no "year" key were last.

That is, it should be like this.
Ascending:
$array = [
  [
    'name' => 'name1',
    'status' => 1,
    'year' => 21
  ],
  [
    'name' => 'name5',
    'status' => 0,
    'year' => 25
  ],
  [
    'name' => 'name4',
    'status' => 0,
    'year' => 30
  ],
  [
    'name' => 'name2',
    'status' => 0,
  ],
  [
    'name' => 'name3',
    'status' => 0,
  ],
]

Descending:
$array = [
  [
    'name' => 'name1',
    'status' => 1,
    'year' => 21
  ],
  [
    'name' => 'name4',
    'status' => 0,
    'year' => 30
  ],
  [
    'name' => 'name5',
    'status' => 0,
    'year' => 25
  ],
  [
    'name' => 'name2',
    'status' => 0,
  ],
  [
    'name' => 'name3',
    'status' => 0,
  ],
]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Abdula Magomedov, 2017-01-25
@Avarskiy

https://github.com/yiisoft/yii2/blob/master/docs/g...
There is a method ArrayHelper::multisort();

M
Maxim Timofeev, 2017-01-25
@webinar

Everything is in the documentation:
www.yiiframework.com/doc-2.0/yii-helpers-arrayhelp... Too lazy
to read?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question