iversonm Posted September 26, 2008 Share Posted September 26, 2008 so lets say you $array=(array(13, 'apples', 'red'), array(15, 'orange', 'orange'), array(1, 'watermelon', 'green')); if i want to sort $array by the number, how do i go about doing that basically i want $array[0]=(1, 'watermelon', 'green') $array[1]=(13, 'apples', 'red') $array[2]=(15, 'orange', 'orange') any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/125901-sorting-arrays/ Share on other sites More sharing options...
ratcateme Posted September 26, 2008 Share Posted September 26, 2008 try this <?php function cust_sort($a,$b){ if($a[0]>$b[0]) return 1; elseif($a[0]<$b[0]) return -1; else return 0; } $array = array(array(13, 'apples', 'red'), array(15, 'orange', 'orange'), array(1, 'watermelon', 'green')); echo "<pre>"; print_r($array); usort($array,"cust_sort"); print_r($array); ?> Scott. Quote Link to comment https://forums.phpfreaks.com/topic/125901-sorting-arrays/#findComment-651069 Share on other sites More sharing options...
sasa Posted September 26, 2008 Share Posted September 26, 2008 just use sort() function Quote Link to comment https://forums.phpfreaks.com/topic/125901-sorting-arrays/#findComment-651193 Share on other sites More sharing options...
F1Fan Posted September 26, 2008 Share Posted September 26, 2008 array_multisort will sort multidimensional arrays: http://us2.php.net/manual/en/function.array-multisort.php Quote Link to comment https://forums.phpfreaks.com/topic/125901-sorting-arrays/#findComment-651227 Share on other sites More sharing options...
Barand Posted September 26, 2008 Share Posted September 26, 2008 try this <?php function cust_sort($a,$b){ if($a[0]>$b[0]) return 1; elseif($a[0]<$b[0]) return -1; else return 0; } $array = array(array(13, 'apples', 'red'), array(15, 'orange', 'orange'), array(1, 'watermelon', 'green')); echo "<pre>"; print_r($array); usort($array,"cust_sort"); print_r($array); ?> Scott. simpler custom function function cust_sort($a, $b) { return $a[0] - $b[0]; } But, as sasa said, if you are sorting on the first elements of the array then sort() will do it. Quote Link to comment https://forums.phpfreaks.com/topic/125901-sorting-arrays/#findComment-651250 Share on other sites More sharing options...
iversonm Posted September 26, 2008 Author Share Posted September 26, 2008 thanks for the responses, im going to try some of this stuff out and then get back to you guys in a little bit and tell you if it worked Quote Link to comment https://forums.phpfreaks.com/topic/125901-sorting-arrays/#findComment-651276 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.