Skip to content

Instantly share code, notes, and snippets.

@nanoninja
Last active August 29, 2015 14:03
Show Gist options
  • Save nanoninja/92da236b193768fc1b10 to your computer and use it in GitHub Desktop.
Save nanoninja/92da236b193768fc1b10 to your computer and use it in GitHub Desktop.
Sorting array with weight
// Sorts by weight
$data = array(
array(
'language' => 'PHP',
'weight' => 50,
),
array(
'language' => 'Java',
'weight' => 20,
),
array(
'language' => 'Ruby',
'weight' => 55,
),
array(
'language' => 'Python',
'weight' => 40,
),
);
$orderBy = 'desc';
usort($data, function ($a, $b) use ($orderBy) {
if ('asc' === $orderBy) {
return $a['weight'] > $b['weight'];
} else {
return $a['weight'] < $b['weight'];
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment