5

我正在尝试执行某种函数来查找(在以下数组中)id 为 2 的对象,并将其移动到数组的顶部。这是原始数组:

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
        )
)

这是我希望它输出的内容(使用移动的数组项):

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
        )
)

任何帮助,将不胜感激。

4

1 回答 1

12
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));
于 2012-09-24T06:34:01.040 回答