Hi I have an array that looks like this
array[
0 => array[
'id' => 1,
'name' => 'Test 1'
'classId' => 3
],
1 => array[
'id' => 1,
'name' => 'Test 1'
'classId' => 15
],
2 => array[
'id' => 1,
'name' => 'Test 1'
'classId' => 17
],
]
And I have another array that contains classIds
like:
classIds = [15, 17, 3]
And I want to sort my array based on classIds
I can do a a double loop to compare it. I am just wondering is there anyother way to get it done?
2
Answers
Actually one loop i enough:
In case you consider
array_search(...)
also a "loop" (though it internally works different), that would be an alternative which produces the same output:The output of both approaches is:
You can sort the array directly and in-place using
usort
and an anonymous comparison function that retrieves the target indices from$classIds
.Given
you can sort
$arr
withwhich outputs
Try it online!