Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional array, find item and move to the top?

I'm trying to do some kind of function that will find (in the following array) the object with the id of 2, and move it to the top of the array. Here's the original array:

Array
(
    [0] => stdClass Object
        (
            [id] => 177
            [startdate] => 2014-08-02
        )

    [1] => stdClass Object
        (
            [id] => 178
            [startdate] => 2014-08-02
        )

    [2] => stdClass Object
        (
            [id] => 2
            [startdate] => 2014-07-28
        )

    [3] => stdClass Object
        (
            [id] => 82
            [startdate] => 2014-07-28

        )

    [4] => stdClass Object
        (
            [id] => 199
            [startdate] => 2013-10-10
        )
)

And here is what I'd like it to output (with the moved array item):

Array
(

    [0] => stdClass Object
        (
            [id] => 2
            [startdate] => 2014-07-28
        )
    [1] => stdClass Object
        (
            [id] => 177
            [startdate] => 2014-08-02
        )

    [2] => stdClass Object
        (
            [id] => 178
            [startdate] => 2014-08-02
        )

    [3] => stdClass Object
        (
            [id] => 82
            [startdate] => 2014-07-28

        )

    [4] => stdClass Object
        (
            [id] => 199
            [startdate] => 2013-10-10
        )
)

Any help would be appreciated.

like image 539
Leanne Seawright Avatar asked Sep 24 '12 06:09

Leanne Seawright


1 Answers

function customShift($array, $id){
    foreach($array as $key => $val){     // loop all elements
        if($val->id == $id){             // check for id $id
            unset($array[$key]);         // unset the $array with id $id
            array_unshift($array, $val); // unshift the array with $val to push in the beginning of array
            return $array;               // return new $array
        }
    }
}

print_r(customShift($data, 2));
like image 66
Mihai Iorga Avatar answered Sep 29 '22 11:09

Mihai Iorga