dongritan5654 2014-06-17 21:06
浏览 44
已采纳

按特定键值排序关联数组

I have the following array:

   $data=array(
   'Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']
    );

This resides in a for each loop in my Codeigniter controller index function:

public function index(){

    $query=$this->My_model->get_data();
    foreach ($query as $row)
    {
           $data=array(
           'Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']
            );

    }
}

Currently if I print_r on $data it would produce:

Array ( [Points] => 500 [Name] => Dave Laus ) 
Array ( [Points] => 1200 [Name] => John Smith ) 
Array ( [Points] => 700 [Name] => Jason Smithsonian ) 

However I would like to sort/order this so that the user with the highest points showing first like this:

Array ( [Points] => 1200 [Name] => John Smith ) 
Array ( [Points] => 700 [Name] => Jason Smithsonian ) 
Array ( [Points] => 500 [Name] => Dave Laus ) 

I want to sort the array by the "Points" key, so that the user with the highest points appear first. I want to re order the array to show from highest to lowest points.

I have tried usort and arsort and ksort. I haven't gotten it to work.

How do I do this?

I tried this in my controller, but it's doesn't work, errors instead:

public function index(){

    $query=$this->My_model->get_data();
    foreach ($query as $row)
    {
           $data=array(
           array('Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']),
            );

           function cmp ($a, $b) {
        return $a['Points'] < $b['Points'] ? 1 : -1;
        }

        usort($data, "cmp");

            print_r($data);


                //I also tried usort($leaders, array('home', 'cmp')); whcih gave no errors, but was the same result as before, not ordered


        }
    }
  • 写回答

3条回答 默认 最新

  • douhuang7263 2014-06-17 21:24
    关注

    Try this:

    function cmp ($a, $b) {
        return $a['Points'] < $b['Points'] ? 1 : -1;
    }
    
    usort($data, "cmp");
    

    See Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题