Skip to content
Advertisement

PHP array sort one item but leave rest in same order

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement