landysaccount Posted August 5, 2009 Share Posted August 5, 2009 Hello. Last weekend I requested help on how to sort a multidimension array; I was requested to look into array_multisort() but, after reading about this function I'm still not able to get the results I need. I currently have the following array that gets populated in a for loop: $data[$num_records]['cust_id'] = $row["eq_cust_id"]; $data[$num_records]['cust_name'] = $customer_name; $data[$num_records]['cust_mac'] = $row["eq_mac_address"]; $data[$num_records]['cust_ip'] = $cust_ip; $num_records++; array_multisort( $data[]['cust_ip'], SORT_NUMERIC); After the loop I would like to be able to sort the array by 'cust_name' or 'cust_ip' but, can't figure out how. Please help. Thanks in advanced. Quote Link to comment https://forums.phpfreaks.com/topic/168887-sorting-multidimension-array/ Share on other sites More sharing options...
Psycho Posted August 5, 2009 Share Posted August 5, 2009 I wouldn't use array_multisort() for this because you would have to first "transform" the array into a different format (see Example#3). A better option, in my opinion, would be to use usort() to define your own sorting function. function sortByName($a, $b) { return strcasecmp($a['cust_name'], $b['cust_name']); } usort($data, "sortByName"); //Records will now be sorted based on name You can also get fancier to sort by two or more columns, i.e. the the primary value is equal then do a secondary (or more) sort on another column. function sortByNameIP($a, $b) { if (strcasecmp($a['cust_name'], $b['cust_name'])==0) { //If name is same, then sort on ip return strcasecmp($a['cust_ip'], $b['cust_ip']); } return strcasecmp($a['cust_name'], $b['cust_name']); } usort($data, "sortByNameIP"); //Records will now be sorted based on name, then IP Note: I have not tested any of this. It may work as expected, not sure. It's late and I'm not in the mood for creating test data. But the idea is sound. Quote Link to comment https://forums.phpfreaks.com/topic/168887-sorting-multidimension-array/#findComment-891101 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.