0

I have a simple PHP array that looks like this...

Array
    (
        [0] => WP_Term Object
            (
                [id] => 455
            )
        [1] => WP_Term Object
            (
                [id] => 738
            )
        [2] => WP_Term Object
            (
                [id] => 88
            )
        [3] => WP_Term Object
            (
                [id] => 905
            )
    )

I am trying to sort this array by putting id 88 at the top but leaving the order the same for everything else. So I end up with...

  Array
    (
        [0] => WP_Term Object
            (
                [id] => 88
            )
        [1] => WP_Term Object
            (
                [id] => 455
            )
        [2] => WP_Term Object
            (
                [id] => 738
            )
        [3] => WP_Term Object
            (
                [id] => 905
            )
    )

I had though about looping through the array first and removing the item with id 88 and then aftwrard reinserting it at the top.

Is this the correct approach or is there a more efficient way?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • It's normal `sort` or `ksort`, isn't it? (just notice, in first array there is twice `0` key, on of them is rewritten) – pavel Jan 15 '21 at 12:39
  • https://www.php.net/manual/en/function.sort.php – Alive to die - Anant Jan 15 '21 at 12:40
  • If keeping the other items in order is important then you'll only be able to use native `*sort` functions if you're on PHP 8 - they aren't stable until that version. There are a few other questions open about stable sorting, but fundamentally that's what you're looking for. For earlier versions, if all you need to do is bubble a single element to the top, then removing and re-inserting is probably clearer. – iainn Jan 15 '21 at 12:43
  • 2
    Don't think of this as sorting; first find the index of item you're looking for, save the element, delete it from the array and then unshift it on the array again. – MatsLindh Jan 15 '21 at 12:43
  • 1
    @fightstarr20 I've written an implementation here: https://gist.github.com/matslindh/c5006d85e93a7f441331bb9dd35866a0 - replace the comparison with something that checks the `id` of the object instead. – MatsLindh Jan 15 '21 at 12:49

1 Answers1

2

At first, what you're trying to do is not sorting. It merely finds an element with the specified ID and then puts that element at the top of array. Whereas sorting is the reorganization of data in a certain order.

Your approach is correct and I think there is no more efficient way.

Kien Nguyen
  • 2,616
  • 2
  • 7
  • 24