php二维数组排序

一.php内置array_multisort方法,eg:

$arr = [
    ['id' => 21,'name' => 'user_1'],
    ['id' => 22,'name' => 'user_2'],
    ['id' => 22,'name' => 'user_3'],
    ['id' => 23,'name' => 'user_1']
];
foreach($arr $key => $val){
   $ID[$key] = $val['id'];
   $Name[$key] = $val['name'];
}
array_multisort($ID,SORT_DESC,$Name,SORT_ASC,$arr);
var_dump($arr);

运行结果如图

2.按照指定键排序

$arr = [
    ['id' => 21,'name' => 'user_1'],
    ['id' => 22,'name' => 'user_2'],
    ['id' => 22,'name' => 'user_3'],
    ['id' => 23,'name' => 'user_1']
];

/**
 * 根据指定键排序
 * @param     array    $array   需要排序的数组
 * @param     string   $key_v   指定键
 * @return    array
 */
function array2dSort($array, $key_v)
{
    $tmp = $last_arr = [];
    foreach ($array as $key => $val)
    {
         $tmp[] = $val[$key_v];
    }
    arsort($tmp);
    foreach ($tmp as $key => $val)
    {
         $last_arr[] = $array[$key];
    }
    return $last_arr;
}
$last_arr = array2dSort($arr,'id');
var_dump($last_arr);
//运行结果同上
添加新评论