Skip to content

Instantly share code, notes, and snippets.

@jasdeepkhalsa
Last active December 15, 2015 13:09
Show Gist options
  • Select an option

  • Save jasdeepkhalsa/5265438 to your computer and use it in GitHub Desktop.

Select an option

Save jasdeepkhalsa/5265438 to your computer and use it in GitHub Desktop.
Sort array with a compare function in PHP (cycles through each element of an array and compares it)
<?php
/*
[0] => stdClass Object
(
[ID] => 1
[name] => Mary Jane
[count] => 420
)
[1] => stdClass Object
(
[ID] => 2
[name] => Johnny
[count] => 234
)
[2] => stdClass Object
(
[ID] => 3
[name] => Kathy
[count] => 4354
)
*/
function cmp($a, $b)
{
return strcmp($a->name, $b->name);
// Note: The array fields may only be accessible via $a['name'], $b['name']
// strcmp function should NOT be used for numbers, instead use < <= > >= comparison operators
}
usort($your_data, "cmp");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment