I have two PHP arrays like so:
- Array of X records containing the ID
of WordPress posts (in a particular
order) - Array of WordPress posts
The two arrays look something like this:
Array One (Sorted Custom Array of WordPress Post IDs)
Array (
[0] => 54
[1] => 10
[2] => 4
)
Array Two (WordPress Post Array)
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 the array of wordpress posts with the order of the ID’s in the first array.
I hope this makes sense, and thanks in advance of any help.
Tom
edit: The server is running PHP Version 5.2.14
This should be quite easy using
usort
, which sorts the array using a user-defined comparison function. The result might look something like this: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
:You could create a nested looping mechanism to match up the order and ids and rebuild a new post array.
You can simply subtract b from a instead of a from b to sort the other direction