0

How do I turn this:

Array
(
    [0] => stdClass Object
        (
            [id] => 123
            [name] => Board
        )
    [1] => stdClass Object
        (
            [id] => 133
            [name] => Staff
        )
)

Into:

Array
(
    [0] => stdClass Object
        (
            [id] => 133
            [name] => Staff            
        )
    [1] => stdClass Object
        (
            [id] => 123
            [name] => Board  
        )
)

Based on this:

Array( 'Staff', 'Board'  )

In other words -- order an array of objects based on an array of values...

4
  • 2
    possible duplicate of Sort an array based on another array? Commented Sep 18, 2014 at 22:54
  • 1
    Don't use 6 year old answers as duplicates. PHP has been reinvented twice since then, see for example my use of anonymous functions to achieve this which wasn't possible back then (without createfunction hacks at least). Also, the solution isn't valid for the intended output of this question. This is therefore not a duplicate, at least of that question. Commented Sep 18, 2014 at 22:57
  • @derp it's not a duplicate question, as the source data doesn't even remotely look like the marked question structurally, and neither does the intended output, requiring a completely different solution. You're saying a BMW M3 and a Fiat 500 are identical cars because they both have a steering wheel. Commented Sep 18, 2014 at 23:19
  • The age isn't a problem, but it does seem different enough to not be a duplicate. I have modified the title to hopefully make that clear. Commented Sep 18, 2014 at 23:57

1 Answer 1

2
$ordering = ['Staff', 'Board'];
usort($myObjects, function($a, $b) use ($ordering) {
    $idx1 = array_search($a->name, $ordering);
    $idx2 = array_search($b->name, $ordering);
    if($idx1 == $idx2)
        return 0;
    elseif($idx1 < $idx2)
        return -1;
    return 1;
});

This example does assume that $ordering will contain all names it's going to encounter. If not you'll have to patch behaviour in there (can't do that because I don't know 'where' you want the unmatched items to sort to).

Sign up to request clarification or add additional context in comments.

3 Comments

gah -- usort! I've been staring at the php manpage on that for over an hour... c'mon brain...
To your comment on $ordering -- what about those that are unmatched getting kicked to the end? Can't guarantee I'll get them all :P
array_search returns FALSE if no match was found. Therefore, for 2 unmatched objects, they are considered equal now (both FALSE), and could end up anywhere in the array, at random. You should either throw an error or introduce more defined behaviour there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.