Two php arrays - sort one array with order value of another

I have two PHP arrays, for example:

  • Array of X records containing the wordpress message identifier (in particular order)
  • Wordpress Message Array

Two arrays look something like this:

Array One (sorted custom array of Wordpress post IDs)

Array ( [0] => 54 [1] => 10 [2] => 4 ) 

Array Two (array of Wordpress posts)

 Array ( [0] => stdClass Object ( [ID] => 4 [post_author] => 1 ) [1] => stdClass Object ( [ID] => 54 [post_author] => 1 ) [2] => stdClass Object ( [ID] => 10 [post_author] => 1 ) ) 

I would like to sort an array of Wordpress posts with identifier order in the first array.

I hope this makes sense, and thanks in advance for any help.

Tom

edit: the server is running PHP version 5.2.14

+7
source share
3 answers

This should be pretty easy with usort , which sorts the array using a custom comparison function. The result might look something like this:

 usort($posts, function($a, $b) use ($post_ids) { return array_search($a->ID, $post_ids) - array_search($b->ID, $post_ids); }); 

Please note that this solution, since it uses anonymous functions and locks , requires PHP 5.3.


One of the simple solutions for this pre-5.3 (dark times!) Is to make a quick loop and then ksort :

 $ret = array(); $post_ids = array_flip($post_ids); foreach ($posts as $post) { $ret[$post_ids[$post->ID]] = $post; } ksort($ret); 
+9
source

You can create a nested loop mechanism to match order and identifiers and rebuild a new message array.

 $new_post_array = array(); foreach($id_array as $id) { //loop through custom ordered ids foreach($post_array as $post) { //for every id loop through posts if($id == $post->ID){ //and when the custom ordered id matches the post->ID new_array[] = $post //push the post on the new array } } } 
+2
source
 $sortOrderMap = array_flip($postIds); usort($posts, function($postA, $postB) use ($sortOrderMap) { return $sortOrderMap[$postA->ID] - $sortOrderMap[$postB->ID]; }); 

You can simply subtract b from a instead of a from b to sort another direction

+2
source

All Articles