1

I have combined two arrays using array_merge, and now need to sort them alphabetically. Problem is I need to compare two different keys,

e.g.

[0] => stdClass Object
(
[id] => 16
[title] => Oranges
)

[1] => stdClass Object
(
[id] => 23
[title] => Apples
)

[2] => stdClass Object
(
[id] => 16
[name] => Bananas
)

I need to compare 'name' properties with each other, as well as with 'title' properties, then sort those alphabetically, (ignoring the id) so that my result would be:

Apples
Bananas
Oranges

However, the function I have here:

function compareItems($a, $b)
{
if ( $a->title < $b->title ) return -1;
if ( $a->title > $b->title ) return 1;
if ( $a->name < $b->name ) return -1;
if ( $a->name > $b->name ) return 1;
return 0;
}

usort($array, "compareItems");

...doesn't combine, but sorts one set of properties (title) then the other (name), thus giving me:

Apples
Oranges
Bananas

I'm hoping I can amend this function to merge the two together - I'm not really a PHP programmer, so any help is much appreciated!

Thanks in advance.

1 Answer 1

3

The comparison function I have below should work for you:

function compareItems($a, $b)
{
    $x = isset($a->title) ? $a->title : $a->name;
    $y = isset($b->title) ? $b->title : $b->name;
    return strcmp($x, $y);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@RT: Glad to have helped! Remember to mark this question as answered by clicking the green checkmark.

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.