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. Quote Link to comment 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'); ?> Quote Link to comment 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 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.