Last active
August 29, 2015 14:03
-
-
Save mamchenkov/ec715f1ab35239a9319b to your computer and use it in GitHub Desktop.
Sorting multidimensional array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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