I have an array of arrays:
Array (
[0] => Array (
[id] = 7867867,
[title] = 'Some Title'),
[1] => Array (
[id] = 3452342,
[title] = 'Some Title'),
[2] => Array (
[id] = 1231233,
[title] = 'Some Title'),
[3] => Array (
[id] = 5867867,
[title] = 'Some Title')
)
The need to go in a specific order:
- 3452342
- 5867867
- 7867867
- 1231233
How would I go about doing that? I have sorted arrays before, and read plenty of other posts about it, but they are always comparison based (i.e. valueA < valueB).
Help is appreciated.
You can use
usort()to dictate precisely how the array is to be sorted. In this case, the$orderarray can be used within the comparison function.The example below uses a
closureto make life easier.The key to this working is having the values that are being compared, be the positions of the
ids within the$orderarray.The comparison function works by finding the positions of the ids of two items to be compared within the
$orderarray. If$a['id']comes before$b['id']in the$orderarray, then the return value of the function will be negative ($ais less so “floats” to the top). If$a['id']comes after$b['id']then the function returns a positive number ($ais greater so “sinks” down).Finally, there is no special reason for using a closure; it’s just my go-to way of writing these sorts of throwaway functions quickly. It could equally use a normal, named function.