Created
March 9, 2019 10:01
-
-
Save Guley/f51dd12e1794ab1b66d1333dfd0d7656 to your computer and use it in GitHub Desktop.
php multidimensional array sort by key
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
$arr = [ | |
"0": [ | |
"id": 1, | |
"schedule_time": "01:01 AM", | |
"day": "Thu" | |
], | |
"1": [ | |
"id": 2, | |
"schedule_time": "04:00 AM", | |
"day": "Sun" | |
], | |
"2": [ | |
"id": 3, | |
"schedule_time": "04:15 AM", | |
"day": "Tue" | |
], | |
"3": [ | |
"id": 4, | |
"schedule_time": "05:00 AM", | |
"day": "Sun" | |
], | |
"4": [ | |
"id": 5, | |
"schedule_time": "05:17 AM", | |
"day": "Tue" | |
] | |
]; | |
$day_map = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; | |
uasort($arr, function($a, $b) use ($day_map) { | |
$c = explode(',', $a['day']); | |
$d = explode(',', $b['day']); | |
for($i = 0, $len = count($c); $i < $len; $i++) { | |
$d1 = @array_search($c[$i], $day_map); | |
$d2 = @array_search($d[$i], $day_map); | |
if($d1 == $d2) { | |
continue; // skip, check the next column | |
} | |
return $d1 - $d2; | |
} | |
}); | |
var_dump($arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment