Multidimensional array, find the element and go to the beginning?

I am trying to execute some function that will find (in the next array) an object with identifier 2 and move it to the beginning 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 would like to output (with the array element moved):

 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.

+4
source share
1 answer
 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)); 
+7
source

Source: https://habr.com/ru/post/1435848/


All Articles