Martyn Ball Martyn Ball - 1 year ago 85
PHP Question

Sorting array of objects by object variable, key being replaced

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download