2010-08-06 19 views
1

在过去的3天里,我一直在尝试对数组进行排序,但没有成功。如何对这个数组进行排序?

我在php文件中首先尝试并在tpl文件中尝试,但是我不能排序我的数组。

你能帮我吗?

这是我的阵列结构(感谢smaty调试工具!):

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 

我希望由上升“ID”进行排序它获得这种结果:

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 

你有什么想法吗?

回答

1

使用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; 
} 

由于zerkms指出,有没有必要使用uksort因为你只需要一个基本的数字比较。这是通过使用简单的ksort()来实现的:

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

使用uksort()时,您的密钥无法按其数值排序。例如,字符串。

+0

在用户功能无需阵列。 – zerkms 2010-08-06 14:30:53

+0

你说得对,ksort就够了。 – 2010-08-06 14:36:06

+0

谢谢,现在好多了! – bahamut100 2010-08-09 07:24:58

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

ksort()将按键排序,保持key => value的关系。你想排序多维数组中的子数组,而不是整个数组。请参阅下面的代码。

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

ksort($array['attributes']); 
ksort($array['attributes_quantity']); 
+0

感谢您的解释 – bahamut100 2010-08-09 07:25:42