two php arrays - sort one array with the value order of another
This should be quite easy using usort
, which sorts the array using a user-defined 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);});
Note that this solution, since it uses anonymous functions and closures, requires PHP 5.3.
One easy solution for this pre-5.3 (the dark ages!) is to do this with 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);
You could create a nested looping mechanism to match up the order and ids and rebuild a new post 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 } }}