Jump to content

[SOLVED] Sorting a multi dimensional array by value of its inner array?


niranjnn01

Recommended Posts

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
Share on other sites

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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.