DaltonRandall Posted November 13, 2017 Share Posted November 13, 2017 Hi there, Let's say I have the following array: Array ( [1] => 4224:3 [2] => 4407:6 [3] => 4403:5 [4] => 4190:4 [5] => 4194:2 [6] => 4185:1 ) I want to sort it based on what follows the colon ( : ) in each value. For example, I would like the result to be: Array ( [6] => 4185:1 [5] => 4194:2 [1] => 4224:3 [4] => 4190:4 [3] => 4403:5 [2] => 4407:6 ) I have found some code to allow me to sort the array as such, but it is resetting all of the keys (which are very important). Does anyone have an efficient way to help me sort the array while keeping the key and value relationship intact? Thanks a bunch in advance for any help! Quote Link to comment Share on other sites More sharing options...
requinix Posted November 13, 2017 Share Posted November 13, 2017 Post your code. If I'm right, taking what you have now and making it work the way you want could be as simple as typing a single character. Quote Link to comment Share on other sites More sharing options...
DaltonRandall Posted November 13, 2017 Author Share Posted November 13, 2017 function cmp($a, $b) { $pieces_a = explode(":", $a); $pieces_b = explode(":", $b); if(!isset($pieces_a[1]) && isset($pieces_b[1])) { return 1; } elseif(!isset($pieces_b[1]) && isset($pieces_a[1])) { return -1; } elseif(!isset($pieces_a[1]) && !isset($pieces_b[1])) { return 0; } if(substr($pieces_a[1], 0, 1) == '0') { return 1; } elseif(substr($pieces_b[1], 0, 1) == '0') { return -1; } $a = substr($pieces_a[1], 0, 1); $b = substr($pieces_b[1], 0, 1); return strcasecmp($a, $b); } Quote Link to comment Share on other sites More sharing options...
DaltonRandall Posted November 13, 2017 Author Share Posted November 13, 2017 And this is the call: usort($sample_array, "cmp"); Quote Link to comment Share on other sites More sharing options...
kicken Posted November 13, 2017 Share Posted November 13, 2017 Indeed, requinix's theory is correct. You just need to be using uasort instead of usort. uasort: Sort an array with a user-defined comparison function and maintain index association 1 Quote Link to comment Share on other sites More sharing options...
DaltonRandall Posted November 13, 2017 Author Share Posted November 13, 2017 Sorry for my ignorance/stupidity. Thank you for the quick replies. <3 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.