多维数组,找到项目并移到顶部?

时间:2012-09-24 06:27:24

标签: php arrays multidimensional-array

我正在尝试做某种函数,它会找到(在下面的数组中)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
        )
)

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:9)

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