How to sort a two-dimensional array in descending order with usort()
$stu = [ ['name'=>'周天子', 'grade'=>'99'], ['name'=>'汉高祖', 'grade'=>'73'], ['name'=>'秦始皇', 'grade'=>'95'], ]; //输出原始数组 echo var_export($stu, true),'<hr>'; //用户自定义回调来进行排序(降序) usort($stu, function ($m, $n){ return strcmp($n['grade'], $m['grade']); // strcmp()函数 (本函数返回: 0 如果两个字符串相等, <0 如果 string1 小于 string2, >0 如果string1 大于 string2 }); //输出排序后的数组 echo var_export($stu, true),'<hr>';
You can refer to it,
<?php
function test($array=array(),$key='',$paixu=true){
$result=array();
foreach($array as $k => $v){
$values[$k]= isset( $v[$key]) ? $v[$key] : '';
}
unset($v);
$paixu ? asort($values ) : arsort($values);
foreach ($values as $k => $v){
$result[$k] = $array[ $k];
return $result;
$data = array(
array('post_id'=>1,'title'=>'How to learn PHP well','reply_num'=>582),
array('post_id'=>2,'title '=>'Summary of common functions for PHP arrays','reply_num'=>182),
array('post_id'=>3,'title'=>'Summary of common functions for PHP strings ','reply_num'=>982),
);
is rsort(), you used the wrong function.
You can refer to it,
<?php
function test($array=array(),$key='',$paixu=true){
$result=array();
foreach($array as $k => $v){
$values[$k]= isset( $v[$key]) ? $v[$key] : '';
}
unset($v);
$paixu ? asort($values ) : arsort($values);
foreach ($values as $k => $v){
$result[$k] = $array[ $k];
}
return $result;
}
$data = array(
array('post_id'=>1,'title'=>'How to learn PHP well','reply_num'=>582),
array('post_id'=>2,'title '=>'Summary of common functions for PHP arrays','reply_num'=>182),
array('post_id'=>3,'title'=>'Summary of common functions for PHP strings ','reply_num'=>982),
);
## $paixuhou=test($data,'reply_num',true); echo "<pre>"; print_r($paixuhou);?>is rsort(), you used the wrong function.