获取数组php中的键,然后用键排序数组?

时间:2012-01-02 02:17:10

标签: php arrays

如果我有一个数组

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
    )
)

然后我会用钥匙排序? 感谢

2 个答案:

答案 0 :(得分:3)

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

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

类似的东西。

答案 1 :(得分: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' );