Multidimensional array, find item and move to the top?

前端 未结 1 1781

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:

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 08:40

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

    0 讨论(0)
提交回复
热议问题