niranjnn01 Posted July 30, 2008 Share Posted July 30, 2008 Hello Everyone, I have a multi dimensional array like this Array ( [userinfo] => Array ( [side] => 0 [occurance] => 0 ) [contactpanel] => Array ( [side] => 0 [occurance] => 1 ) [mydetails] => Array ( [side] => 0 [occurance] => 2 ) [myblogs] => Array ( [side] => 0 [occurance] => 3 ) [myfriends] => Array ( [side] => 1 [occurance] => 0 ) [mygallery] => Array ( [side] => 1 [occurance] => 1 ) ) [yes this is the print_r output of the array] I want to sort the inner arrays according to the value of the "occurance" . How is that possible?... is there a function in php which can do this? Thanks Rakesh. Link to comment https://forums.phpfreaks.com/topic/117366-solved-sorting-a-multi-dimensional-array-by-value-of-its-inner-array/ Share on other sites More sharing options...
troy_mccormick Posted July 30, 2008 Share Posted July 30, 2008 It is possible...I believe you have to write your own function to compare... Here it is: <?php $products = array( array( 'TIR', 'Tires', 100 ), array( 'OIL', 'Oil', 10 ), array( 'SPK', 'Spark Plugs', 4 ) ); function compare($x, $y) { if ( $x[1] == $y[1] ) return 0; else if ( $x[1] < $y[1] ) return -1; else return 1; } usort($products, 'compare'); ?> Link to comment https://forums.phpfreaks.com/topic/117366-solved-sorting-a-multi-dimensional-array-by-value-of-its-inner-array/#findComment-603667 Share on other sites More sharing options...
niranjnn01 Posted July 31, 2008 Author Share Posted July 31, 2008 Hello troy_mccormick, Your suggesstion was useful. I was able to do a little modification to it to suit my needs, - one of which was that, since i was using an associative array, I wanted to retained to key=>value association. So i used the function uasort() . Here is the code <?php $products = array ( 'userinfo' => Array ( 'side' => 0, 'occurance' => 0 ), 'contactpanel' => Array ( 'side' => 0, 'occurance' => 1 ), 'myblogs' => Array ( 'side' => 0, 'occurance' => 2 ), 'mydetails' => Array ( 'side' => 0, 'occurance' => 3 ), 'myfriends' => Array ( 'side' => 1, 'occurance' => 0 ), 'mygallery' => Array ( 'side' => 1, 'occurance' => 1 ), ); function compare($x, $y) { if ( $x['occurance'] == $y['occurance'] ) return 0; else if ( $x['occurance'] < $y['occurance'] ) return -1; else return 1; } uasort($products, 'compare'); print_r($products); ?> Thanks for the help Rakesh Link to comment https://forums.phpfreaks.com/topic/117366-solved-sorting-a-multi-dimensional-array-by-value-of-its-inner-array/#findComment-604358 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.