Skip to content

Instantly share code, notes, and snippets.

@mamchenkov
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mamchenkov/ec715f1ab35239a9319b to your computer and use it in GitHub Desktop.
Save mamchenkov/ec715f1ab35239a9319b to your computer and use it in GitHub Desktop.
Sorting multidimensional array
<?php
// Nested array to sort
$data = array(
'Guy' => array(
array('id' => 1, 'title' => 'This'),
array('id' => 7, 'title' => 'Boo'),
array('id' => 9, 'title' => 'Boo'),
array('id' => 3, 'title' => 'Broken'),
),
'Girl' => array(
array('id' => 2, 'title' => 'Down'),
array('id' => 8, 'title' => 'Service'),
array('id' => 4, 'title' => 'Protocol'),
),
);
/**
* Sort tickets by title ASC and id DESC
*/
function ticketsSort($a, $b) {
if ($a['title'] == $b['title']) {
if ($a['id'] == $b['id']) {
return 0;
}
// DESC
return ($a['id'] > $b['id']) ? -1 : 1;
}
// ASC
return ($a['title'] > $b['title']) ? 1 : -1;
}
// If you don't like array_walk and stuff :)
foreach ($data as $person => $tickets) {
usort($tickets, 'ticketsSort');
$data[$person] = $tickets;
}
print_r($data);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment