0

I have this array of options, and some value of an internal array is the "ID"

[options] => Array (
    [0] => Array (
        [id] => 1088
        [label] => John
    )
    [1] => Array (
        [id] => 1089
        [label] => Peter
    )
    [2] => Array (
        [id] => 1050
        [label] => Mary
    )
    ....

On the other hand, I have this array:

$array_sort = array(1089, 1050, 1088, ...);

I would like the options array of the first array is sorted (looking the "id") based on the $array_sort.

I know how to do it in a very dirty way (with a lot of loops and temporary arrays), but I guess there's some smart solution of array_* functions to do this.

Thank you !

1
  • Thank you for the edition, @Qirel Commented Feb 10, 2017 at 19:11

1 Answer 1

1

You could use array_filter to limit the options to only those in the sorted array, then usort to sort them based on their position in the $array_sort array using array_search:

$sorted = array_filter($options, function($arr) use($array_sort) {
    return in_array($arr['id'], $array_sort);
});
usort($sorted, function($a, $b) use($array_sort) {
    return array_search($a['id'], $array_sort) - array_search($b['id'], $array_sort);
});
// $sorted should now be the sorted array
Sign up to request clarification or add additional context in comments.

4 Comments

$sorted returns just 1 :-(
Sorry, it sorts the array in-place. I'll edit the code.
I can't edit, but you missed the "use ($array_sort)" in the two functions in order to get the array_sort right scope, since it's outside the functions ;-) and IT WORKS !! THANK YOU
Thanks for pointing that out. I added it. I guess that's what happens when you try to write code in the answer box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.