0

Hi gotta array of Std class objects like

Array
(
[0] => stdClass Object(
    [id] => 2
    [name] => sven
)

[1] => stdClass Object(

    [id] => 88
    [name] => pat
)

[2] => stdClass Object(
    [id] => 63
    [name] => dan
)

)

and a order array like

$order = array(88,2,63);

how to sort it by my custom order? i tried to usort like

usort($myArray, function ($a, $b) use ($order) {
    $pos_a = array_search($a, $order);
    $pos_b = array_search($b, $order);
    return $pos_a - $pos_b;
});

with no success because of the std class array_search will not work

1 Answer 1

1

you can filp the order array, then compare the $order array of their value in 0, 1, 2.

$order = array_flip($order);
usort($myArray, function($a, $b)use($order){return $order[$a->id] > $order[$b->id];});
Sign up to request clarification or add additional context in comments.

Comments

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.