排序多维数组帮助

时间:2011-01-26 16:09:58

标签: php arrays sorting multidimensional-array

我试图按season_number排序这个数组但是我不确定要使用哪个函数,因为我认为我需要自定义排序?有什么想法吗?

Array
(
    [0] => Array
        (
            [season_number] => 7
            [show_id] => 21
            [show_seasons_id] => 14
        )

    [1] => Array
        (
            [season_number] => 6
            [show_id] => 21
            [show_seasons_id] => 31
        )

    [2] => Array
        (
            [season_number] => 1
            [show_id] => 21
            [show_seasons_id] => 40
        )

    [3] => Array
        (
            [season_number] => 2
            [show_id] => 21
            [show_seasons_id] => 41
        )
)

2 个答案:

答案 0 :(得分:1)

试试这个:

foreach ($array as $key => $val) {
    $newArr[$key] = $val['season_number'];
}
array_multisort($newArr, SORT_ASC, $array);

其中$ array是您打印出来的数组。

答案 1 :(得分:1)

您可以将usort功能与'compare'功能一起使用:

function compare_my_elements( $arr1, $arr2 ) {
   $s1=$arr1["season_number"];
   $s2=$arr2["season_number"];
   if( $s1 == $s2 ) return 0;
   return ( $s1 > $s2 ? 1 : -1 );
}

usort( $my_md_array, compare_my_elements );