How would I re-order an array of objects like:
Array
(
[0] => stdClass Object
(
[term_id] => 3
[name] => Name
)
[1] => stdClass Object
(
[term_id] => 1
[name] => Name2
)
[2] => stdClass Object
(
[term_id] => 5
[name] => Name
)
)
According to the objects term_id, against a custom defined array of ids:
$order_by = array( 5,3,1 )
What I’m using now is below, but I feel like I’m not taking advantage of some advanced sorting functions PHP has… Can anyone tell me what would work better?
$sorted_terms = array();
$order_by = array( 5,3,1 );
foreach( $order_by as $id ) {
foreach ( $terms as $pos => $obj ) {
if ( $obj->term_id == $id ) {
$sorted_terms[] = $obj;
break;
}
}
}
Basically, the rank of your terms in their sorted order is the same as the rank of their corresponding ids, which happens to be the array keys in the
$order_byarray. So we just need to flip that array to get the mapping of ids to ranks, and then sort using it with a custom comparison function.Here’s a simple code snippet that should work:
The above code would work with PHP 5.3 or later.
Here’s the same thing with pre 5.3 PHP:
The important functions are: