dsjpqpdm620596 2015-10-23 10:05
浏览 83

排名php多维数组

I'm trying to rank a group of scores. So I've taken the input from a users form and sorted them from largest to smallest in a multidimensional array, so then that I can search the array for the user and retrieve the index to get its "rank" however I appear to be doing something totally wrong! any help on where I'm going wrong would be greatly appreciated, or if there is a better way entirely!

Thank you

PHP Code:

if ( isset( $_POST['submit'] ) ) {

    $size = $num_rows;
    $p = 0;
    $myarray = array();

    while ( $p < $size ) {
        $myarray[] = array( "user" => $user[$p], "data" => $scanrate[$p] );
        $p++;
    }

    $sort = array();

    foreach ( $myarray as $k => $v ) {
        $sort['data'][$k] = $v['data'];
    }

    array_multisort( $sort['data'], SORT_DESC, $myarray );

    for ( $i = 0; $i < $num_rows; $i++ ) {
        $key = array_search( $i, array_column( $myarray, 'user' ) );

        if ( !$key ) {
            $key = $num_rows;
        }
        //this is stored into my database
        echo "<br>User " . $user[$i] . " scan rate " . $scanrate[$i] . " rank " . $key;
    }
} 
  • 写回答

2条回答 默认 最新

  • dongpengqin3898 2015-10-23 10:32
    关注

    You do useless code to do this sort, use the usort() function like :

    while($p < $size)  
    { 
      $myarray[] = array("user" => $user[$p], "data" => $scanrate[$p]); 
      $p++; 
    } 
    
    usort($myarray, function($a, $b) {
        return $a['data'] - $b['data'];
    });
    

    Now your $myarray is sorted and you can search and do what you want.

    评论

报告相同问题?

悬赏问题

  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退