Sulman Posted May 4, 2010 Share Posted May 4, 2010 Hi all, I have an array that i need to order but I'm looking for some advice as how to do it. The array looks like this: <?php $myarray[0]['order'] = 39; $myarray[0]['title'] = "title 1"; $myarray[1]['order'] = 39; $myarray[1]['title'] = "title 2"; $myarray[2]['order'] = 5; $myarray[2]['title'] = "title 3"; $myarray[3]['order'] = 0; $myarray[3]['title'] = "title 4"; etc... ?> I need to be able to order the array in ascending order based on the "order" element so it will look like this: <?php $myarray[0]['order'] = 0; $myarray[0]['title'] = "title 4"; $myarray[1]['order'] = 5; $myarray[1]['title'] = "title 3"; $myarray[2]['order'] = 39; $myarray[2]['title'] = "title 1"; $myarray[3]['order'] = 39; $myarray[3]['title'] = "title 2"; etc... ?> Any ideas how i would achieve this? Normally it would be pretty easy: simply use the order as the index of the array, but the problem with that is that I would lose one because there are two 39's! Any clues?! Thanks Quote Link to comment https://forums.phpfreaks.com/topic/200687-best-way-to-sort-this-array/ Share on other sites More sharing options...
Ken2k7 Posted May 4, 2010 Share Posted May 4, 2010 You need usort. Read about it. function c ($a, $b) { if (!array_key_exists('order', $a) || !array_key_exists('order', $b)) return 2; if ($a['order'] == $b['order']) return strcmp($a['title'], $b['title']); return $a['order'] < $b['order']? -1 : 1; } usort($myarray, 'c'); var_dump($myarray); Quote Link to comment https://forums.phpfreaks.com/topic/200687-best-way-to-sort-this-array/#findComment-1053116 Share on other sites More sharing options...
Sulman Posted May 4, 2010 Author Share Posted May 4, 2010 Thanks for that. I'll look into your solution. Quote Link to comment https://forums.phpfreaks.com/topic/200687-best-way-to-sort-this-array/#findComment-1053141 Share on other sites More sharing options...
teamatomic Posted May 4, 2010 Share Posted May 4, 2010 array_multisort is the function for sorting multidimensional arrays foreach ($myarray as $key => $row) { $count[$key] = $row['count']; array_multisort($count, SORT_ASC, $myarray); print_r($myarray); } just replace$row['count'] with whatever you want sorted, in your case it would be $row['order']. HTH Teamatomic Quote Link to comment https://forums.phpfreaks.com/topic/200687-best-way-to-sort-this-array/#findComment-1053202 Share on other sites More sharing options...
Sulman Posted May 5, 2010 Author Share Posted May 5, 2010 Thanks teamatomic that function has worked a treat! Many thanks! Quote Link to comment https://forums.phpfreaks.com/topic/200687-best-way-to-sort-this-array/#findComment-1053493 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.