I have the following Arrays:
$inputArray = Array(
[0] => stdClass Object (
[id] => 8
)
[1] => stdClass Object (
[id] => 7
)
[2] => stdClass Object (
[id] => 5
)
)
$sortingArray = [5,8,1]
I'm looking an efficient way to sort the input array by the id "map of values".. expected output should be $inputArray reordered so that 3rd item would be first, first item would be 2nd etc.
thanks!
First and foremost, if your input array is the result set of a MySQL query, you should be sorting the data via an ORDER BY clause.
FIELD()
is an excellent tool for the job, with slight weirdness that you need to reverse your sorting logic and writeDESC
after the function.Resource: https://www.electrictoolbox.com/mysql-order-specific-field-values/ (scroll down to "gotcha")
SQL Fiddle Demo: http://sqlfiddle.com/#!9/6b996f/1
Beyond that, I'll offer two refined versions of Nigel's and Eddie's solutions leveraging some php7+ goodness. Which one you choose to implement will have to do with:
id
values to "survive" the processSolution #1: usort() and null coalescing operator
PHP Demo
*note that I could have passed
$outlier
into the custom function scope as a seconduse
argument and replaced all of the$order['']
variables with$outlier
, but I opted to append the outlier data into the lookup array.*I used parentheses in my custom function not only to improve readability, but to guarantee that the evaluation is performed as intended -- I didn't actually bother to check if the evaluation is the same without the parenthetical grouping.
Solution #2: array_replace() a flipped & filtered sort array with a keyed array
(PHP Demo)
*note this won't generate an oversized array of
null
values and it will not remove values that are "falsey".*I will again state that the use of
array_column()
will damage the data if there are duplicateid
values in the input array.You can use
array_flip
to make a temporary array. This will flip the array means the values will be the key.Use
usort
to sort the array.This will result to:
I've used a few things here, the main thing is that I use the sorting array as a target for an
array_replace()
and I usearray_column()
to index the objects by (this needs PHP 7.0+ to work with objects)...The
array_filter()
will remove any elements which aren't in the input array but in the sorting array. Thearray_fill_keys()
is used instead ofarray_flip()
so that I can set a null value, which allows the filter to work.