tags:

views:

53

answers:

4

Hello,

For the last 3 days, I have been trying to sort an array, but without success.

I tried in the php file first and in the tpl file, but it was impossible for me to sort my array.

Can you help me please ??

This is the structure of my array (thanks to the smaty debug tool !) :

Array (5)
attributes => Array (4)
  23 => "1L"
  24 => "3.5L"
  21 => "50ml"
  22 => "350ml"
name => "Contenance"
is_color_group => "0"
attributes_quantity => Array (4)
  23 => 1
  24 => 500
  22 => 500
  21 => 500
default => 21

I wish to sort it by the ascending "id" to obtain this kind of result :

Array (5)
attributes => Array (4)
  21 => "50ml"
  22 => "350ml"
  23 => "1L"
  24 => "3.5L" 
name => "Contenance"
is_color_group => "0"
attributes_quantity => Array (4)
  21 => 500
  22 => 500
  23 => 1
  24 => 500  
default => 21

Have you an idea ?

+1  A: 

http://php.net/manual/en/array.sorting.php

del.ave
I read it, but I didn't understood arrays with "imbricated" arrays
bahamut100
+1  A: 

Use uksort:

uksort( $your_array['attributes'], 'my_sort_func' );
uksort( $your_array['attributes_quantity'], 'my_sort_func' );

function my_sort_func( $a, $b )
{
    if( $a == $b )
        return 0;

    return ($a < $b) ? -1 : 1;
}

As zerkms noted, there no need to use uksort as you only need a basic numeric comparison. This is achieved using simply ksort():

ksort( $your_array['attributes'] );
ksort( $your_array['attributes_quantity'] );

Use uksort() when your keys cannot be sorted by its numerical value. For example, strings.

clinisbut
no need in user-function.
zerkms
You're right, ksort is enough.
clinisbut
Thanks, it's better now !
bahamut100
A: 
ksort($arr['attributes']);
ksort($arr['attributes_quantity']);
zerkms
A: 

ksort() will sort by key, maintaining the key => value relationship. You want to sort the sub-arrays in your multidimensional array, not the entire array. See the code below.

http://www.php.net/manual/en/function.ksort.php

ksort($array['attributes']);
ksort($array['attributes_quantity']);
Scott Saunders
thanks for the explications
bahamut100