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.

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');
?>

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.