0

I have some simple PHP code that formats an object containing information about some songs. I try and sort this information using usort(), but I can't quite get the sorting to work correctly.

print_r($my_songs_object) returns (heavily simplified):

stdClass Object
(
    [0] => stdClass Object
        (
            [track] => stdClass Object
                (
                    [name] => ZZZ
                )
        )

    [1] => stdClass Object
        (
            [track] => stdClass Object
                (
                    [name] => YYY
                )
        )
)

My PHP sorting code:

usort($my_songs_object, function($a, $b) {
    return ucfirst($a->track->name) > ucfirst($b->track->name) ? 1 : -1;
});

After running the above usort(), $my_songs_object always returns the data sequentially.

In the above example, item 1 should come before item 0.

How can I get modify the usort function to achieve the desired output?

EDIT:

The original object is being created an array_merge of two preexisting objects that need to be combined. I am using the following code to combine them:

$my_songs_object = (object)array_merge((array)$a->items, (array)$b->items);

Perhaps modifying the way in which the objects are combined would make sorting the combined $my_songs_object easier?

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
  • 1
    Does usort even work on a stdClass (as opposed to an array)? – user2864740 Oct 11 '15 at 00:04
  • 1
    @frosty: _“usort is a pain in the ass to use”_ – no it’s not, it’s a great tool to accomplish basically any kind of custom sorting you can think of. It’s a very handy thing, you just need to know what you’re doing. – CBroe Oct 11 '15 at 01:52
  • Why don’t you simply sort that stuff _before_ you cast it into an object? – CBroe Oct 11 '15 at 01:53
  • @Cbroe You brought up a good point. As it turns out, I don't actually *need* it to be cast into an object at all! Simply removing that fixed the problem, thanks a bunch :) – Obsidian Age Oct 11 '15 at 02:00

1 Answers1

0

The answer was that as it turns out, I didn't need to typecast the array into an object at all after the initial merge.

Changing:

$my_songs_object = (object)array_merge((array)$a->items, (array)$b->items);

To:

$my_songs_object = array_merge((array)$a->items, (array)$b->items);

Solved the problem. Thanks to @Cbroe for bringing this to my attention :)

I'll mark this as resolved in two days.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71