N
N
nemovalex2021-10-08 23:58:32
Yii
nemovalex, 2021-10-08 23:58:32

Sorting an array in Yii2?

The bottom line is that I have a category table that is linked to itself. That is, a category can have a parent category from the same table by the "parent_id" key. The task is that I need a list of all categories in the form of an array, but sorted as follows:

[
      'Родительская категория',
      'Дочерня категория 1',
      'Дочерняя категория 2',
      'Дочерняя категория 3',
      'Родительская категория 2',
      'Дочерняя категория 1',
      'Дочерняя категория 2'
]

And at the end I need to make an array consisting of id = key, title = value pairs, I know how to do this (ArrayHalper::map) but how can I sort the first array?
Initial array:
6160b0d40b8d9801795318.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nemovalex, 2021-10-09
@nemovalex

Found a solution, who will be useful:

SELECT * FROM `categories` ORDER BY COALESCE(NULLIF(parent, 0), id),
        (parent = 0) DESC,
        id

If that table is linked in this way parent_id = id;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question