Page 1 of 1

SORTING ISSUE OF COMPLEX ARRAY

Posted: Wed Nov 05, 2008 6:42 am
by bhushanahirrao
~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


Hi All,

Please see following array:

Code: Select all

 
Array
(
    [1] => Array
        (
            [HoraXp] => Array
                (
                    [14] => 1
                    [total] => 1
                )
 
        )
 
    [2] => Array
        (
            [SpoiledSan] => Array
                (
                    [15] => 1
                    [22] => 1
                    [total] => 2
                )
 
        )
 
    [3] => Array
        (
            [3b3nJean] => Array
                (
                    [13] => 1
                    [total] => 1
                )
 
        )
 
    [4] => Array
        (
            [roma89] => Array
                (
                    [13] => 1
                    [18] => 1
                    [22] => 1
                    [24] => 2
                    [total] => 5
                )
 
        )
 
    [5] => Array
        (
            [derosz] => Array
                (
                    [13] => 1
                    [total] => 1
                )
 
        )
 
)
 

I want sort this array by [total] in desc order. Can u please help me.


~pickle | Please use [ code=html ], [ code=php ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: SORTING ISSUE OF COMPLEX ARRAY

Posted: Wed Nov 05, 2008 7:47 am
by papa
Give it a first try and show us your code.

Re: SORTING ISSUE OF COMPLEX ARRAY

Posted: Wed Nov 05, 2008 10:17 am
by pickle
usort() might be what you need.

Please don't feel you need to SHOUT YOUR SUBJECT IN ALL CAPS!

We can read just fine.

Re: SORTING ISSUE OF COMPLEX ARRAY

Posted: Wed Nov 05, 2008 10:46 am
by rbx
In this case I usually create a 1-dim reference array that contains same keys as top-level keys of original array and values fill with values to be sorted. Then sort this array and you have access-array to your original array that defines desired order. Example, say we that your original array is stored in $orig_array:

Code: Select all

 
foreach($orig_array as $key=>$data)
{
   foreach($data as $props)
  {
     $access_array[$key] = $props['total'];
  };
};
 
arsort($access_array, SORT_NUMERIC);
 
Then $access_array keys are sorted in desired order and you can use it as access to the original array.