Search code examples
phparrayssortingmultidimensional-arrayrotation

Rotate an array of objects so that an object with a specific property is the first element


I have the following array:

$myarray = Array (
[1] => stdClass Object ( 
    [ID] => 1 
    [current] => 
)

[2] => stdClass Object ( 
    [ID] => 2 
    [current] => 1 
)

[3] => stdClass Object ( 
    [ID] => 3 
    [current] =>
)

[4] => stdClass Object ( 
    [ID] => 4 
    [current] =>
)

[5] => stdClass Object ( 
    [ID] => 5 
    [current] =>
)
)

And I need to sort it, having the value current as the first, and the afterwards all the items that were originally after that current one, and the items that were originally before would be the last ones on the result array.

So the new array would look like this:

Array (
[1] => stdClass Object ( 
    [ID] => 2 
    [current] => 1 
)

[2] => stdClass Object ( 
    [ID] => 3 
    [current] =>
)

[3] => stdClass Object ( 
    [ID] => 4 
    [current] =>
)

[4] => stdClass Object ( 
    [ID] => 5 
    [current] =>
)

[5] => stdClass Object ( 
    [ID] => 1 
    [current] => 
)
)

Solution

  • If you want to keep the same order of element do not sort your array but rotate it until the current element is first, e.g.

    while($myarray[0]['current']<>1) {
      array_push($myarray, array_shift($myarray));
    }