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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With