PHP二维数组按照指定键排序

排序函数:

/**
 * 二维数组按照指定键排序
 * @param $array 需要排序的数组
 * @param $on 指定的键名
 * @param $order 升序SORT_ASC还是降序SORT_DESC,默认为升序
 */
function arraySort ($array, $on, $order = SORT_ASC)
{
    $newArray = array();
    $sortableArray = array();
    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortableArray[$k] = $v2;
                    }
                }
            } else {
                $sortableArray[$k] = $v;
            }
        }
        switch ($order) {
            case SORT_ASC:
                asort($sortableArray);
                break;
            case SORT_DESC:
                arsort($sortableArray);
                break;
        }
        foreach ($sortableArray as $k => $v) {
            $newArray[] = $array[$k];
        }
    }
    return $newArray;
}

使用示例:

//一个二维数组
$stock = array(
    0 => array(
        'stockcode' => 600007,
        'stockname' => '中国国贸',
        'time' => '2011-12-31',
    ),
    1 => array(
        'stockcode' => 600007,
        'stockname' => '中国国贸',
        'time' => '2012-6-30',
    ),
    2 => array(
        'stockcode' => 600007,
        'stockname' => '中国国贸',
        'time' => '2012-5-29',
    )
);
//按照time降序排列
$stock = arraySort ( $stock, 'time', SORT_DESC);
print_r($stock);

得到结果:

Array

(

[0] =>  Array
(

[stockcode] => 600007

[stockname] => 中国国贸

[time] => 2012-6-30

),
[1] =>  Array
(

[stockcode] => 600007

[stockname] => 中国国贸

[time] => 2012-5-29

),
[2] =>  Array
(

[stockcode] => 600007

[stockname] => 中国国贸

[time] => 2011-12-31

),
)