How does usort() sort a two-dimensional array in descending order?
弦知音
弦知音 2019-02-15 17:14:42
0
5
1260

How to sort a two-dimensional array in descending order with usort()

弦知音
弦知音

reply all(3)
弦知音
$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),

);


## $paixuhou=test($data,'reply_num',true);

echo "<pre>";

print_r($paixuhou);

?>

刘毅

is rsort(), you used the wrong function.

  • reply Ignore the key name and sort by value, sort() ascending order, rsot() descending order, usort() callback, I am asking how to descend using the callback method, it is not that the function is used wrongly.
    弦知音 author 2019-02-16 08:51:08
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template