2012-01-02 58 views
1

如果我有一个阵列获取数组php中的密钥,然后用键排序数组?

Array 
(
[3] => Array 
    (
     [0] => title = title dffgfghfdg 
     [1] => 2-title2 
     [2] => content = content 2 
    ) 

[1] => Array 
    (
     [0] => title = title erer 
     [1] => 1-title1 
     [2] => content = content 1 
    ) 

[0] => Array 
    (
     [0] => title = title sdfdf 
     [1] => 4-title4 
     [2] => content = content 4 
    ) 

[2] => Array 
    (
     [0] => title = titledfdf df 
     [1] => 3-title3 
     [2] => content = content 3 
    ) 
) 

,我将尽[1]是关键。因为我会在[1]中对数组进行排序..?

可能会

Array 
(
[2-title2] => Array 
    (
     [0] => title = title dffgfghfdg 
     [1] => 2-title2 
     [2] => content = content 2 
    ) 

[1-title1] => Array 
    (
     [0] => title = title erer 
     [1] => 1-title1 
     [2] => content = content 1 
    ) 

[4-title4] => Array 
    (
     [0] => title = title sdfdf 
     [1] => 4-title4 
     [2] => content = content 4 
    ) 

[3-title3] => Array 
    (
     [0] => title = titledfdf df 
     [1] => 3-title3 
     [2] => content = content 3 
    ) 
) 

的话,我会用钥匙排序? 谢谢

+0

你的问题有点不清楚。你在问如何用非整数键对数组进行排序? – Will 2012-01-02 02:22:02

回答

3

使用foreach()来转换数组,然后使用kso​​rt()。

foreach($a as $k => $v) { 
    $b[$v[1]] = $v; 
} 
ksort($b); 

就是这样的。

+0

谢谢亚历克西斯,它工作得很好! 我很开心... – 2012-01-02 03:45:38

3

为此使用usorthttp://php.net/manual/en/function.usort.php

function user_cmp($a, $b) 
{ 
    if($a[1] == $b[1]) return 0; 
    return ($a[1] < $b[1]) ? -1 : 1; 
} 

$arr = array(...); 
usort($arr, 'user_cmp'); 
+0

+1,但我简化user_cmp只是'返回strcmp($ a [1],$ b [1]);'。 – cmbuckley 2012-01-02 16:25:37