0

I have got an array of object instances, I need to sort these based on what a function within the object returns.

So basically my object has got 2 variables, the function will add them together, and then return the result, the list of objects need to be sorted based on this.

My sorting code:

function cmp($a, $b)
{
  if ($a->calcPoints() == $b->calcPoints()) {
     return 0;
  }
  return ($a->calcPoints() > $b->calcPoints()) ? -1 : 1;
}
usort($teamData, "cmp");

Without using the usort function I get the following when dumping my array:

Key: "Hull City FC" Value: {"win":3,"draw":2,"loss":8,"goalFor":11,"goalConc":28} Key: "Leicester City FC" Value: {"win":3,"draw":4,"loss":6,"goalFor":16,"goalConc":22}

Once I used the usort function, my keys are being replaced like so:

Key: 0 Value: {"win":10,"draw":1,"loss":2,"goalFor":29,"goalConc":10} Key: 1 Value: {"win":9,"draw":3,"loss":1,"goalFor":29,"goalConc":12}

How can I stop this?

1
  • Have you tried using uasort? Commented Nov 27, 2016 at 19:01

2 Answers 2

2

If you lookup usort() in the manual, you'll find:

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

uasort(), however, will: "Sort an array with a user-defined comparison function and maintain index association". Go ahead and try that, it should be what you're looking for.

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

Comments

1

You should use uasort function instead of usort. According to PHP documentation:

uasort — Sort an array with a user-defined comparison function and maintain index association

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.