开发者

How to sort this array?

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开发者_如何学Go 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 ?


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.


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


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


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']);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜