search

Home  >  Q&A  >  body text

How does usort() sort a two-dimensional array in descending order?

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

弦知音弦知音2190 days ago1305

reply all(5)I'll reply

  • 弦知音

    弦知音2019-02-16 09:40:40

    $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>';


    reply
    1
  • 刘毅

    刘毅2019-02-15 21:45:06

    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);

    ?>

    reply
    0
  • 刘毅

    刘毅2019-02-15 21:44:36

    is rsort(), you used the wrong function.

    reply
    0
  • 弦知音

    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.

    弦知音 · 2019-02-16 08:51:08
  • Cancelreply