如何基于值对数组进行排序

时间:2015-04-07 03:14:57

标签: php arrays sorting multidimensional-array

$arr['a']['studentname'] = "john";

$arr['b']['studentname'] = "stefen";

$arr['c']['studentname'] = "alex";

是否可以使用用户定义的函数进行排序:

usort( $arr )


uasort( $arr )


uksort( $arr )

所以基于我需要传递的值,数组应该排序! 预期产出:

如果当前值

Array
(
    [c] => Array
        (
            [studentname] => alex

        )

    [a] => Array
        (
            [studentname] => john

        )

    [b] => Array
        (
            [studentname] => stefen

        )

)  

如果当前值

 Array
    (

[b] => Array
            (
                [studentname] => stefen

            )
 [a] => Array
            (
                [studentname] => john

            )
        [c] => Array
            (
                [studentname] => alex

            )

    )  

提前致谢

2 个答案:

答案 0 :(得分:1)

如果我理解了这个问题,你可以使用一个简单的字符串比较回调:

$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";

// A-Z
uasort($arr, function($a, $b) {
  return strcmp($a['studentname'], $b['studentname']);
});

print_r($arr);

// Z-A
uasort($arr, function($a, $b) {
  return strcmp($b['studentname'], $a['studentname']);
});

print_r($arr);

答案 1 :(得分:0)

试试这个:
对于PHP版本> 5.3:

$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";

uasort($arr, function($a, $b) {
    return strcmp($a['studentname'], $b['studentname']);
});

对于PHP版本< 5.3:

$arr['a']['studentname'] = "john";
$arr['b']['studentname'] = "stefen";
$arr['c']['studentname'] = "alex";

function sort_by($a, $b) {
    return strcmp($a['studentname'], $b['studentname']);
}

uasort($arr, 'sort_by');