-1

I have an array that looks like this:

[
  1 => [
    'title' => 'a title',
    'status' => 'active'
  ],
  2 => [
    'title' => 'a title 2',
    'status' => 'disabled'
  ],
  1 => [
    'title' => 'a title 3',
    'status' => 'not active'
  ]
]

My goal is to group/sort them by status order 1. active 2. not active 3. disabled

So basically like so:

[
  1 => [
    'title' => 'a title',
    'status' => 'active'
  ],
  2 => [
    'title' => 'a title 3',
    'status' => 'not active'
  ]
  3 => [
    'title' => 'a title 2',
    'status' => 'disabled'
  ]
]

I know I'll probably need to write a loop and execute some array functions but my concern is how can I determine the order of the statuses, which is prio over the other.

michael
  • 421
  • 6
  • 21
  • 1
    That's one of the reasons why people use numeric statuses, to make it easy to sort. Other than that, something along the lines of `usort()` with a custom comparison function to handle the strings? – droopsnoot Apr 02 '20 at 12:01
  • 1
    Does this answer your question? [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – CBroe Apr 02 '20 at 12:05
  • 1
    The mentioned duplicate explains how to work with `usort` in general. To simply “translate” your status texts into an “order”, I would recommend to just use `array_search`. Put your three text values into an array, in the correct order - and then “search” for the value of the items you are comparing in your usort callback function in there. That will return the corresponding index 0, 1 or 2, and that is a value you can easily use for > / < / == comparisons. – CBroe Apr 02 '20 at 12:07

1 Answers1

0

You will need to use usort. In order to save some time i would assing a value to each status option:

    $mappings = [
        'active' => 0,
        'not active' => 1,
        'disabled' => 2
    ];
    $toSort = [
        1 => [
            'title' => 'a title',
            'status' => 'active'
        ],
        2 => [
            'title' => 'a title 2',
            'status' => 'disabled'
        ],
        3 => [
            'title' => 'a title 3',
            'status' => 'not active'
        ]
    ];
    usort($toSort, static function (array $x, array $y) use ($mappings) {
       return $mappings[$x['status']] - $mappings[$y['status']];
    });

By using a mapping you can simple subtract the values. If the value y comes after the value x, the result will be negative, thus positioning it after x.

If you use php 7.4, the usort code can even be a oneliner:

usort($toSort, static fn(array $x, array $y) => $mappings[$x['status']] - $mappings[$y['status']];);
Ghlen
  • 659
  • 4
  • 14